Download presentation
Presentation is loading. Please wait.
Published byGregory Charles Modified over 9 years ago
1
L EC. 04: C LASSES, O BJECTS AND M ETHODS 0
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
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
4
C ONTENTS OF A J AVA 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. 3
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
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
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
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
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
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
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 Fall. 2014 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
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
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
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. 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. 14
16
F IGURE OF MEMORY ALLOCATION 15 sedan suv2 suv1 passengers 5 feulCapacity 70 milePerGallon 32 passengers 7 feulCapacity 90 milePerGallon 26
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
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
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 }
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.
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
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
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
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
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
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
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
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. Starts executing the invoked method within its computation environment. Fall. 2014 27 Java Programming
29
E XAMPLE OF ARGUMENT EVALUATION The output of the following program is “going gone gone”. Fall. 2014 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. Fall. 2014 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. 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 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."); } Fall. 2014 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"); } Fall. 2014 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.
34
C ONSTRUCTORS 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 33 Java Programming
35
C ONSTRUCTORS 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 34 Java Programming
36
E XAMPLE OF USING CONSTRUCTORS class 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 35 Java Programming Remember javac automatically adds a default constructor for DemoMyClass class.
37
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 36 Java Programming
38
E XAMPLE OF USING this class 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 37 Java Programming
39
C OMPARISON VARIABLE CATEGORIES Fall. 2014 38 Java Programming Analysis FactorFieldsParametersLocal variables UsageStoring class or object properties Passing input values to methods Temporarily storing computation results Where declaredInside a class definition, but outside a method definition In the method headerInside a method definition or a code block How declaredtype name [ = value];type name;type name [ = value]; How initializedDefault, explicit, or by a constructor By the caller during invocation Explicit initialization, NO DEFAULT ScopeWithin class or outside the class Within the methodWithin the method or specific statement block
40
L OADING 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 39 Java Programming
41
E XAMPLE 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 40 Java Programming
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.