41
LEC. 04: CLASSES, OBJECTS AND METHODS 1

L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT Fundamentals of Java classes Reference variables Creating objects Fundamentals of methods

Embed Size (px)

Citation preview

Page 1: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

1

LEC. 04: CLASSES, OBJECTS AND METHODS

Page 2: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

2

CONTENT

Fundamentals of Java classes Reference variables Creating objects Fundamentals of methods Class and instance methods Parameters and arguments Using the keyword this Constructors Fields Comparisons among variables categories Loading classes

Page 3: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

3

JAVA CLASSES AND OBJECTS

In Java, a class (類別 ) is a template/blueprint that defines the both the data and the code that will operate on that data.

Each class definition is a data type. Java uses a class specification to construct objects. Objects (物件 ) are instances of a class by specifying

object states. The methods(方法 ) and fields(欄位 ) that constitute a class are

called members(成員 ) of the class.

Page 4: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

4

CONTENTS OF A JAVA CLASS

A java class may consist of the following 7 types of components. Constructors (建構子 ) Class fields (類別欄位 ) Instance fields (實例欄位 ) Class methods (類別方法 ) Instance methods (實例方法 ) Static initializers (靜態初始化 ) Non-static initializers (非靜態初始化 )

All these components are option. The simplest class is “class Foo{}”.

There is no ordering restriction for defining the members of a class.

Page 5: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

5

CONSTRUCTORS

A constructor of a class is a method which is executed only when an object of the class is created/instantiated.

A class must consist of at least one constructor. A class may consist of more than one constructor.

Page 6: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

6

CLASS FIELDS AND INSTANCE FIELDS

Class fields of a class are variables for storing data which are shared among all the objects of the class. Class fields of a class can be directly accessed by all methods

defined in the class. Class fields of a class exist when the class is loaded by the

class loader. Instance fields of a class are variables for storing the

attribute values of an object of the class. Instance fields of a class can be only directly accessed by the

instance methods and non-static initializers defined in the class.

Instance fields of a class exist only when objects of the class are created.

Each object has its own instance fields.

Page 7: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

7

CLASS METHODS AND INSTANCE METHODS

Class methods of a class are methods associated with the class. It means they can be used whenever the class exists, i.e. the

class is loaded into JVM. Class methods of a class are executed within the space of the

class, i.e. all the fields referred in a class method are class fields.

Instance methods of a class are methods associated with objects of the class. It means they can be used only when objects are created. Instance methods are executed within the space of the object

which activates the methods.

Page 8: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

8

STATIC INITIALIZERS AND NON-STATIC INITIALIZERS

Static initializers of a class are methods which are executed only when the class is loaded into JVM. They are executed only once.

Non-static initializers of a class are methods which are executed whenever an object of the class is created.

Page 9: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

9

SYNTAX FOR DEFINING CLASSES

A class definition is composed of two parts: class heading and class body.

The heading of a definition includes the access restriction and class name.

The class name must immediately follow the keyword class.

The class body follows the heading and is enclosed by a pair of curly braces.<access-modifier> class <class-name> { // class body }

Page 10: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

10

AN EXAMPLE OF CLASS DEFINITIONpublic class Vehicle { int passengers; // instance field int feulCapacity; // instance field int milePerGallon; // // instance field Vehicle(int noPassengers, int feulCap, int mpg) { //constructor passengers = noPassengers; feulCapacity = feulCap; milePerGallon = mpg; } public void setMilePerGallon(int mpg) { // instance method milePerGallon = mpg; // changing the content } public int getMilePerGallon() { // instance method return milePerGallon; // reading the content }}

Page 11: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

11

Java Program

ming

COHESION AND COUPLING

A good class definition must satisfy two metrics: high cohesion and low coupling.

Cohesion refers how the components of a class are related. High cohesion means that the components of a class are close

related. Coupling refers the interdependencies among classes.

Low coupling means that the dependencies among classes are loose

Fall. 2014

Page 12: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

12

EXAMPLE OF CREATING AND REFERENCING AN OBJECT1. class Car {2. public static void main(String args[]) {3. Vehicle sedan; // declaring a reference variable4. Vehicle suv1, suv2; // declaring reference variables5. sedan = new Vehicle(5, 70, 32); //creating a Vehicle object6. suv1 = new Vehicle(7, 90, 26); // creating another Vehicle //object7. suv2 = suv1; // NO vehicle object created // suv1 and suv2 pointing to the same Vehicle // object8. sedan.milePerGallon = 45; // accessing the instance field9. System.out.println("sedan: " + sedan.getMilePerGallon());10. suv2.setMilePerGallon(30); // sending message11. System.out.println ("suv1: " + suv1.getMilePerGallon());12. }13. }

Page 13: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

13

has-a RELATION BETWEEN CLASSES

If a class, say ClassA, declares a reference variable of another class, say ClassB, then “ClassA has-a ClassB” relation exists between these two classes. For example, in the sample program on p.11, the relation

“Car has-a Vehicle” exists. The has-a relation is not commutative.

For example, “Vehicle has-a Car” relation does not exist.

Page 14: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

14

REFERENCE VARIABLES

A reference variable is a variable with a class data type. The content of a reference variable is a starting memory

address of a memory block which is used to save an object. The members of an object can be accessed through the

reference variable pointing to the object by using the dot operator (.). As in the previous example, sedan.milePerGallon is used to

access the instance field milePerGallon of the Vehicle object pointed by sedan.

Also, suv2.setMilePerGallon(30) invokes the method of the Vehicle object pointed by suv2.

Conventionally, the name of an object is the same as the name of the reference variable pointing to the object.

Page 15: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

15

CREATING OBJECTS In Java, an object can be created by using the new operator. Syntax form

new <class-constructor>(<constructor-parameter>); The operand of the new operator is an invocation of the constructor of

the class based on which an object is created. The new operator dynamically allocates (that is, allocates at run

time) memory block for saving the information related to an object, then executes the constructor of the class to initialize the object state and finally returns a reference to it. A reference, in Java, means the starting address of a memory block.

Usually, the reference returned from new operator will be stored in a reference variable.

Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class.

Page 16: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

16

FIGURE OF MEMORY ALLOCATION

sedan

suv2

suv1

passengers5

feulCapacity70

milePerGallon32

passengers7

feulCapacity90

milePerGallon26

Page 17: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

17

LINE 7 OF THE SAMPLE PROGRAM

In line 7, the assignment operator copies the result of the expression of suv1 to the variable suv2.

The result of evaluating suv1 is the content of suv1 which is the reference of an object.

Therefore, both suv1 and suv2 point to the same object.

Page 18: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

18

LIN 9 AND 11 OF THE SAMPLE PROGRAM

In line 9, the getMilePerGallon() message is sent to and received by object sedan, the method getMilePerGallon() works on the memory space inside the memory block pointed by sedan, so the output is 45.

In line 11, the getMilePerGallon() message is sent to and received by object suv1, the method getMilePerGallon() works on the memory space inside the memory block pointed by suv1, so the output is 30.

Page 19: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

19

DECLARING FIELDS

Fields, including both class and instance fields, are variables declared inside the class body but outside the method body.

Class fields declared with the keyword static. Instance fields declared without the keyword static. Example

Both class and instance fields are automatically initialized to binary 0.

class MyClass { static int var1; // declare a class field int var2; // declare a instance field}

Page 20: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

20

DEFAULT VALUES FOR FIELDSData type Default value

boolean false

char ‘\u0000’

byte 0

short 0

int 0

long 0L

float 0.0F

double 0.0D

any class type null

The null is a keyword which means pointing to nothing.

Page 21: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

21

METHODS

A method contains one or more statements to complete a designated task.

A method definition is composed of two parts: method heading and method body.

The heading of a method definition includes the access restriction, type of returned data, method name and parameter (參數 ) list. In Java, a method, within its scope, is uniquely identified by the

name and parameter list, so the combination of name and parameter list is called the signature (簽名 ) of the method.

The method body includes local variable declarations and statements which are enclosed by a pair of curly braces. Local variables are used to store temporary results which are

generated during executing statements.

Page 22: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

22

METHODS

The type of returned data can be any valid type, including primitive and class type.

If the method does not return a value, its return type must be void.

The parameter-list is a sequence of type and identifier pairs separated by commas.

Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, the parameter list will be

empty. Arguments of a message are prepared by the method which

sends the message.

Page 23: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

23

TYPES OF METHODS

Java supports two types of methods: class and instance. Class methods are declared with the keyword static. Instance methods are declared without the keyword

static. Class methods of a class can be directly invoked by both

class and instance methods of the same class. Instance methods of a class can be only directly invoked

by instance methods of the same class.

Page 24: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

24

INVOKING METHODS

A method is activated when it is invoked by statements in another method.

A method can be invoked by three possible forms. If the calling and called methods are defined in the same

class: <method-name>(<argument-list>) Calling instance method of an object:

<object-name>.<method-name>(<argument-list>) Calling class method of a class:

<class-name>.<method-name>(<argument-list>)

Page 25: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

25

PARAMETERS AND ARGUMENTS

A parameter is a special kind of variable, used in a method to refer to one of the pieces of data provided as input to the method.

An argument is a value sent from the caller to the invoked method.

Parameters are declared inside the pair of parentheses that follow the method’s name.

A method can have more than one parameter by declaring each parameter, separating one from the next with a comma.

The parameter declaration syntax is the same as that used for variables. Each parameter must have its own declaration including the type

and name.

Page 26: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

26

PARAMETERS AND ARGUMENTS

A parameter is within the scope of its method, and aside from its special task of receiving an argument, it acts like a local variable.

A parameter is initialized by its corresponding argument, so it cannot be initialized with declaration. For example, void foo(int par = 1) {} is illegal

The mapping between parameters and arguments is based on their positions. The value of the first argument is copied into the first

parameter, the value of the second argument into the second parameter, and so on.

Page 27: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

27

EXAMPLE OF INVOKING METHODS1. class Vehicle {2. // copy all the statements on page 9 to here3. public double range(int gallons) {4. double mtd;5. mtd = gallons * getMilePerGallons(); // invoking method in the same6. // class7. return mtd; // terminating the method and returning a value8. }9. }10. class AddingGas {11. public static void main(String args[]) 12. throws java.io.IOException {13. java.util.Scanner sc = new java.util.Scanner(System.in);14. int gallons;15. int distance;16. Vehicle sedan = new Vehicle(5, 70, 36); 17. System.out.println(“Enter the gallons of gas in your car:”);18. gallons = sc.nextInt();19. System.out.println(“Enter the distance to travel:”);20. distance = sc.nextInt();21. if(sedan.range(gallons) <= distance) System.out.println(“Add gas now”);22. }23. }

Another way to input data from keyboard.

Check the APIs of java.util.Scanner class

Page 28: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

28

Java Program

ming

WHEN A METHOD IS INVOKED …

The execution of the caller stops right at the invocation. JVM memorizes the operation immediately next to the

invocation, so called the return address, such as the “<=“ in line 20 of the program on page 25.

The arguments are evaluated from left to right and the results are copied to corresponding parameters. Carefully examine the example given in the next slide.

The computation environment of the invoked method is pushed into the system stack (系統堆疊 ). The system stack is a JVM control memory space used to save

the computation environment for each method execution. Starts executing the invoked method within its

computation environment.

Fall. 2014

Page 29: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

29

Java Program

ming

EXAMPLE OF ARGUMENT EVALUATION

The output of the following program is “going gone gone”.

Fall. 2014

public class TestArgEva { public static void main(String… args) { String s = “going”; toDo(s, s = “gone”, s); } static void toDo(String p1, String p2, String p3) { System.out.println(p1 + “ “ + p2 + “ “ + p3); } }

Page 30: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

30

Java Program

ming

EXITING FROM METHODS

There are two cases causing the exit of method execution. The execution flow reaches the end curly brace of a method. A return statement is executed.

Two usages of return For methods declared with void, use the following form to

terminate method execution. (It is not necessary!)

return; For methods declared with any types except void, use the

following form to return a value to the calling method (that is the one sends the message) and terminate method execution.

return <expression>; The type of data returned by a method must be compatible with the return

type specified by the method. The invocation of a non-void method is treated as an expression and the

returned value is the result of evaluating the expression.

Fall. 2014

Page 31: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

31

Java Program

ming

WHEN A METHOD TERMINATES …

When a method completes by executing a return command with expression, the expression is evaluated, the result is returned to the caller, and then the method terminates.

When a method completes by executing a return command without expression, the method simply terminates.

After the method terminating, the computation environment of the terminating method is removed from the system stack and the caller resumes at the return address.

Fall. 2014

Page 32: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

32

Java Program

ming

EXAMPLE OF USING PARAMETERS AND ARGUMENTS

class ChkNum { boolean isEven(int x) { // return true if x is even if((x%2) == 0) return true; else return false; }}

class ParmDemo { public static void main(String args[]) { ChkNum e = new ChkNum(); if(e.isEven(10)) System.out.println("10 is even."); if(e.isEven(9)) System.out.println("9 is even."); if(e.isEven(8)) System.out.println("8 is even."); }}

Fall. 2014

It is 10 at the first time invocation, 9 at the second time

and 8 at the third time

Page 33: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

33

Java Program

ming

EXAMPLE OF USING PARAMETERS AND ARGUMENTS

class Factor { boolean isFactor(int a, int b) { if( (b % a) == 0) return true; else return false; }}

class IsFact { public static void main(String args[]) { Factor x = new Factor(); if(x.isFactor(2, 20)) System.out.println("2 is factor"); if(x.isFactor(3, 20)) System.out.println("this won't be displayed"); }}

Fall. 2014

At the first call, a and b are 2 and 20.

At the second time, a and b are 3 and 20.

Page 34: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

34

Java Program

ming

CONSTRUCTORS

A constructor of a class is syntactically similar to a method, but with no explicit return type, which initializes an object or performs any other startup procedures required to create a fully formed object when it is created.

Each class has at least one constructor. If there is no constructor specified in a class, javac

automatically adds a default constructor (預設建構子 ). A default constructor is a non-arg, i.e. without parameter, constructor

and does nothing, except calls the non-arg constructor of its super class.

If there is a constructor defined, no default constructor will be added by javac.

Fall. 2014

Page 35: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

35

Java Program

ming

CONSTRUCTORS

The name of a class constructor must be the same as the class name.

A class may have more than one constructor, but with different parameter list.

Constructors are only activated by the new operator.

Fall. 2014

Page 36: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

36

Java Program

ming

EXAMPLE OF USING CONSTRUCTORSclass MyClass { int x, y; MyClass() { x = 0; y = 0; } MyClass(int a) { x = a; y = 0; } MyClass(int a, int b) { x = a; y = b; }}

class DemoMyClass { public static void main(String args[]) { MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(5); MyClass obj3 = new MyClass(4, 3 + 4); DemoMyClass obj4 = new DemoMyClass(); }}

Fall. 2014

Remember javac automatically adds a

default constructor for DemoMyClass class.

Page 37: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

37

Java Program

ming

this KEYWORD

When a method is called, it is automatically passed an implicit argument that is a reference to the object receiving a message (that is, the object on which the method is called).

This reference is named this.

Fall. 2014

Page 38: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

38

Java Program

ming

EXAMPLE OF USING thisclass Pwr { double base; int exp; double val; Pwr(double base, int exp) { // instance fields base and exp are // hidden by parameters with the same name this.base = base; // this.base refers to the instance field // base refers to the parameter this.exp = exp; this.val = 1; // both this.val and val refer to the instance field if(exp==0) return; for( ; exp>0; exp--) this.val = this.val * base; } double get_pwr() { return this.val; }}

Fall. 2014

Page 39: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

39

Java Program

ming

COMPARISON VARIABLE CATEGORIES

Fall. 2014

Analysis Factor Fields Parameters Local variables

Usage Storing class or object properties

Passing input values to methods

Temporarily storing computation results

Where declared Inside a class definition, but outside a method definition

In the method header Inside a method definition or a code block

How declared type name [ = value]; type name; type name [ = value];

How initialized Default, explicit, or by a constructor

By the caller during invocation

Explicit initialization, NO DEFAULT

Scope Within class or outside the class

Within the method Within the method or specific statement block

Page 40: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

40

Java Program

ming

LOADING CLASSES

When a class is referred, as an argument of the command java or used by executing a class, the class is loaded into JVM memory space by the class loaders.

JVM creates a java.lang.Class object to represent the loaded class.

The java.lang.Class class provides many services to process classes.

The reflection mechanism can be done by using these services provided by Class class. Reflection is commonly used by programs which require the

ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

Fall. 2014

Page 41: L EC. 04: C LASSES, O BJECTS AND M ETHODS 0. C ONTENT  Fundamentals of Java classes  Reference variables  Creating objects  Fundamentals of methods

41

Java Program

ming

EXAMPLE OF USING java.lang.Class

class DemoClass { public static void main(String args[]) { DemoClass obj = new DemoClass(); Class classObj = obj.getClass(); // get the Class object // representing the class from // which obj is created System.out.println(“The class name of obj: “ + obj.getName()); }}

Fall. 2014