33
JAVA PROGRAMMING 2 CH 04: CLASSES, OBJECTS AND METHODS (I) 1 J a v a P r o g r a m m i n g

J AVA P ROGRAMMING 2 C H 04: C LASSES, O BJECTS AND M ETHODS (I) 0 Java Programming

Embed Size (px)

Citation preview

Java Program

ming

1

JAVA PROGRAMMING 2 CH 04: CLASSES, OBJECTS AND METHODS (I)

2

Java Program

ming

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

3

Java Program

ming

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.

4

Java Program

ming

CONTENTS OF A JAVA CLASS

A java class may consist of the following 7 types of components. Constructors (建構子 ) Class fields (靜態資料成員 ) (or 類別欄位 ) Instance fields (實例資料成員 ) (or實例欄位 ) Class methods (靜態方法成員 ) (or 類別方法 ) Instance methods (實例方法成員 ) (or實例方法 ) 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.

5

Java Program

ming

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.

6

Java Program

ming

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.

7

Java Program

ming

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.

8

Java Program

ming

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.

9

Java Program

ming

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 }

10

Java Program

ming

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

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

12

Java Program

ming

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

13

Java Program

ming

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.

14

Java Program

ming

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.

15

Java Program

ming

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.

16

Java Program

ming

FIGURE OF MEMORY ALLOCATION

sedan

suv2

suv1

passengers5

feulCapacity70

milePerGallon32

passengers7

feulCapacity90

milePerGallon26

17

Java Program

ming

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.

18

Java Program

ming

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.

19

Java Program

ming

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}

20

Java Program

ming

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.

21

Java Program

ming

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.

22

Java Program

ming

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.

23

Java Program

ming

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.

24

Java Program

ming

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

25

Java Program

ming

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.

26

Java Program

ming

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.

27

Java Program

ming

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

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.

29

Java Program

ming

EXAMPLE OF ARGUMENT EVALUATION

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

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

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.

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.

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."); }}

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

and 8 at the third time

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"); }}

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

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