4. Writing Classes

22
4. Writing 4. Writing Classes Classes Based on Based on Java Software Development, 5 Java Software Development, 5 th th Ed. Ed. By Lewis &Loftus By Lewis &Loftus

description

4. Writing Classes. Based on Java Software Development, 5 th Ed. By Lewis &Loftus. Topics. Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields. User-defined Classes. Java program consists of a set of classes . - PowerPoint PPT Presentation

Transcript of 4. Writing Classes

Page 1: 4. Writing Classes

4. Writing 4. Writing ClassesClasses

Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.

By Lewis &LoftusBy Lewis &Loftus

Page 2: 4. Writing Classes

TopicsTopics

Anatomy of a Class

Encapsulation

Anatomy of a Method

Graphical Objects

Graphical User Interfaces

Buttons and Text Fields

Page 3: 4. Writing Classes

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.

Page 4: 4. Writing 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()

Page 5: 4. Writing Classes

ClassesClasses

A class can contain data declarations A class can contain data declarations and method declarationsand method declarations

MAXVALUE, faceValue

Data declarations

Method declarations

Page 6: 4. Writing Classes

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

Page 7: 4. Writing Classes

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){…}

Page 8: 4. Writing Classes

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”;}}

Page 9: 4. Writing Classes

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).

Page 10: 4. Writing Classes

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.

Page 11: 4. Writing Classes

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

Page 12: 4. Writing Classes

TopicsTopics

Anatomy of a Class

Encapsulation

Anatomy of a Method

Graphical Objects

Graphical User Interfaces

Buttons and Text Fields

Page 13: 4. Writing Classes

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

Page 14: 4. Writing Classes

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

Page 15: 4. Writing Classes

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

Page 16: 4. Writing Classes

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

Page 17: 4. Writing Classes

TopicsTopics

Anatomy of a Class

Encapsulation

Anatomy of a Method

Graphical Objects

Graphical User Interfaces

Buttons and Text Fields

Page 18: 4. Writing Classes

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

Page 19: 4. Writing Classes

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

Page 20: 4. Writing Classes

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

Page 21: 4. Writing Classes

Example ProgramsExample Programs

Transactions.javaTransactions.java Account.javaAccount.java

Page 22: 4. Writing Classes

TopicsTopics

Anatomy of a Class

Encapsulation

Anatomy of a Method

Graphical Objects

Graphical User Interfaces

Buttons and Text Fields