Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "J AVA P ROGRAMMING 2 C H 04: C LASSES, O BJECTS AND M ETHODS (I) 0 Java Programming."— Presentation transcript:

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

2 C ONTENT  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 1 Java Programming

3 J AVA 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. 2 Java Programming

4 C ONTENTS OF A J AVA 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. 3 Java Programming

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. 4 Java Programming

6 C LASS 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. 5 Java Programming

7 C LASS 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. 6 Java Programming

8 S TATIC 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. 7 Java Programming

9 S YNTAX 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. class { // class body } 8 Java Programming

10 A N EXAMPLE OF CLASS DEFINITION public 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 } 9 Java Programming

11 C OHESION 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 10 Java Programming

12 E XAMPLE OF CREATING AND REFERENCING AN OBJECT 1. class Car { 2. public static void main(String args[]) { 3. Vehicle sedan; // declaring a reference variable 4. Vehicle suv1, suv2; // declaring reference variables 5. sedan = new Vehicle(5, 70, 32); //creating a Vehicle object 6. suv1 = new Vehicle(7, 90, 26); // creating another Vehicle //object 7. suv2 = suv1; // NO vehicle object created // suv1 and suv2 pointing to the same Vehicle // object 8. sedan.milePerGallon = 45; // accessing the instance field 9. System.out.println( " sedan: " + sedan.getMilePerGallon()); 10. suv2.setMilePerGallon(30); // sending message 11. System.out.println ( " suv1: " + suv1.getMilePerGallon()); 12. } 13. } 11 Java Programming

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. 12 Java Programming

14 R EFERENCE 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. 13 Java Programming

15 C REATING OBJECTS  In Java, an object can be created by using the new operator.  Syntax form new ( );  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. 14 Java Programming

16 F IGURE OF MEMORY ALLOCATION 15 sedan suv2 suv1 passengers 5 feulCapacity 70 milePerGallon 32 passengers 7 feulCapacity 90 milePerGallon 26 Java Programming

17 L INE 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. 16 Java Programming

18 L IN 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. 17 Java Programming

19 D ECLARING 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. 18 class MyClass { static int var1; // declare a class field int var2; // declare a instance field } Java Programming

20 D EFAULT VALUES FOR FIELDS 19 Data typeDefault value booleanfalse char‘\u0000’ byte0 short0 int0 long0L float0.0F double0.0D any class typenull The null is a keyword which means pointing to nothing. Java Programming

21 M ETHODS  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. 20 Java Programming

22 M ETHODS  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. 21 Java Programming

23 T YPES 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. 22 Java Programming

24 I NVOKING 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: ( )  Calling instance method of an object:. ( )  Calling class method of a class:. ( ) 23 Java Programming

25 P ARAMETERS 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. 24 Java Programming

26 P ARAMETERS 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. 25 Java Programming

27 E XAMPLE OF INVOKING METHODS 1. class Vehicle { 2. // copy all the statements on page 9 to here 3. public double range(int gallons) { 4. double mtd; 5. mtd = gallons * getMilePerGallons(); // invoking method in the same 6. // class 7. return mtd; // terminating the method and returning a value 8. } 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. } 26 Another way to input data from keyboard. Check the APIs of java.util.Scanner class Java Programming

28 W HEN 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. 27 Java Programming

29 E XAMPLE OF ARGUMENT EVALUATION  The output of the following program is “going gone gone”. 28 Java Programming 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 E XITING 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 ; 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. 29 Java Programming

31 W HEN 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. 30 Java Programming

32 E XAMPLE 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."); } 31 Java Programming It is 10 at the first time invocation, 9 at the second time and 8 at the third time

33 E XAMPLE 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"); } 32 Java Programming At the first call, a and b are 2 and 20. At the second time, a and b are 3 and 20.


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

Similar presentations


Ads by Google