4. writing classes based on java software development, 5 th ed. by lewis &loftus
TRANSCRIPT
4. Writing 4. Writing ClassesClasses
Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.
By Lewis &LoftusBy Lewis &Loftus
TopicsTopics
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
User-defined ClassesUser-defined Classes
Java program consists of a set of Java program consists of a set of classesclasses..
One class must contain a method One class must contain a method namd namd main()main()—which becomes the —which becomes the starting point of the program.starting point of the program.
We have been using classes from the We have been using classes from the Java Standard Library (API).Java Standard Library (API).
You will now write your own classes.You will now write your own classes.
Classes & ObjectsClasses & Objects
Class hasClass has NameName State (attributes)State (attributes) Behavior (methods)Behavior (methods)
E.g., to represent dice in a game E.g., to represent dice in a game program:program: Name: Die (singular of dice)Name: Die (singular of dice) Attributes: MAXVALUE, faceValueAttributes: MAXVALUE, faceValue Methods: constructor, roll(), Methods: constructor, roll(),
toString(), getFacevalueValue() toString(), getFacevalueValue()
ClassesClasses
A class can contain data declarations A class can contain data declarations and method declarationsand method declarations
MAXVALUE, faceValue
Data declarations
Method declarations
Classes & ObjectsClasses & Objects
Necessary methodsNecessary methods Constructor – to create an object of Die Constructor – to create an object of Die
classclass toString – returns the String value that toString – returns the String value that
represents the object in some wayrepresents the object in some way getFaceValue – to return the current getFaceValue – to return the current
face value of a dieface value of a die RollingDice.javaRollingDice.java Die.javaDie.java
Constructor MethodConstructor Method
Constructor method(s) is used to Constructor method(s) is used to instantiate objects.instantiate objects.
It can set initial values for objects.It can set initial values for objects. It has the same name as the class name.It has the same name as the class name. It has no return type.It has no return type. E.g.,E.g.,Die(){…}Die(){…}Student (String name, int age){…}Student (String name, int age){…}
toString() MethodtoString() Method
Every class should include a toString() Every class should include a toString() method, which returns some String value method, which returns some String value representing an object of the class.representing an object of the class.
It is called It is called automaticallyautomatically when an object is when an object is passed to the passed to the System.out.println() mthod.System.out.println() mthod.
E.g.,E.g.,String toString() {String toString() { return “Die object”; return “Die object”;}}
Scope of DataScope of Data
Scope of dataScope of data Area in the program where data can be Area in the program where data can be
referenced (can be used) referenced (can be used) Data declared at the class level can be Data declared at the class level can be
reference in all methods of the class reference in all methods of the class (global visibility).(global visibility).
Data declared in a method can be Data declared in a method can be referenced only in that method (local referenced only in that method (local visibility).visibility).
Instance DataInstance Data
In class Die, In class Die, faceValuefaceValue is called instance is called instance data, because each instance of Die data, because each instance of Die maintains its own memory for faceValue maintains its own memory for faceValue with a value.with a value.
Each instance (object) of class Die shares Each instance (object) of class Die shares its methods, but maintains its own data its methods, but maintains its own data space.space.
Every time class Die is instantiated, a new Every time class Die is instantiated, a new memory for faceValue is allocated.memory for faceValue is allocated.
UML DiagramUML Diagram
UML (Unified Modeling Language) UML (Unified Modeling Language) diagrams show relationships among diagrams show relationships among classes and objects.classes and objects.
RollingDice
main (args : String[]) : void
Die
faceValue : int
Die()roll() : intsetFaceValue (int value) : voidgetFaceValue() : inttoString() : String
TopicsTopics
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
EncapsulationEncapsulation Two views of a classTwo views of a class
Internal (all variables and code visible)Internal (all variables and code visible) External (only public elements are visible)External (only public elements are visible)
InterfaceInterface Method names with parameters—no Method names with parameters—no
internal details of method bodyinternal details of method body Methods and instance variables are Methods and instance variables are
encapsulated – encapsulated – combined into a single combined into a single entity, for the purpose ofentity, for the purpose of Information hidingInformation hiding Data and behavior abstractionData and behavior abstraction
Visibility ModifiersVisibility Modifiers ModifierModifier specifies some characteristic of specifies some characteristic of
method or data—e.g., method or data—e.g., finalfinal.. Visibility ModifiersVisibility Modifiers
publicpublic Can be referenced from anywhereCan be referenced from anywhere
protectedprotected Can be referenced from subclasses Can be referenced from subclasses
(derived from a class)(derived from a class) privateprivate
Visible only from within the classVisible only from within the class defaultdefault
Visible to all classes within the same Visible to all classes within the same packagepackage
Visibility ModifiersVisibility Modifiers
Instance variablesInstance variables Should not be declared publicShould not be declared public Should not be accessible directlyShould not be accessible directly Should be accessed or modified via public methodsShould be accessed or modified via public methods
Methods Methods that provide services should be publicthat provide services should be public that provide support for methods should not be that provide support for methods should not be
publicpublic ConstantsConstants
Can be public, because they cannot be modifiedCan be public, because they cannot be modified
Accessors and MutatorsAccessors and Mutators
Given: class Given: class FractionFraction AccessorsAccessors
Methods which return the value of an Methods which return the value of an instance variableinstance variable
E.g., getNumerator(), getDenominator()E.g., getNumerator(), getDenominator() MutatorsMutators
Mehtods which change the value of an Mehtods which change the value of an instance variableinstance variable
E.g., setNumerator(), setDenominator()E.g., setNumerator(), setDenominator() Required for each instance variableRequired for each instance variable
TopicsTopics
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
Method HeaderMethod Header A method declaration begins with a A method declaration begins with a method headermethod header
boolean isEven (int num)
methodname
returntype
parameter list
The parameter list specifies the typeand name of each parameter
The name of a parameter in the methoddeclaration is called a formal parameter
Method BodyMethod Body The method header is followed by the The method header is followed by the method bodymethod body
Boolean isEven (int num)
{ boolean result; if (num % 2 == 0) result = true; else result = false;
return result;}
The return expression must be consistent with the return type
result is a local variable.
It is created each time the method is called, and is destroyed when it finishes executing
Invoking a MethodInvoking a Method
boolean isEven (int num)
{ boolean result; if (num % 2 == 0) result = true; else result = false; return result;}
If (isEven(a * b - c)){ …}else{ …}
Actual parameter
Formal parameter
The value of actual parameter is copied to the formal parameter
Example ProgramsExample Programs
Transactions.javaTransactions.java Account.javaAccount.java
TopicsTopics
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields