25
LEC. 06: CLASS DETAILS 1

L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT Class method [review] Access control Passing arguments Method overloading Variable-length

Embed Size (px)

Citation preview

Page 1: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

1

LEC. 06: CLASS DETAILS

Page 2: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

2

2015 SPRING CONTENT

Class method [review] Access control Passing arguments Method overloading Variable-length Arguments [ 不測驗,可列補充教材 ] Recursion Using the keyword static Nested classes

Shadowing

Page 3: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

3

CLASSES AND OBJECTS

In Java, a class is a template/blueprint that defines 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. Data members are referred to as instance variables

Page 4: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

4

1. /* A program that uses the Vehicle class.

2. Call this file VehicleDemo.java

3. */

4. class Vehicle {

5. int passengers; // number of passengers

6. int fuelcap; // fuel capacity in gallons

7. int mpg; // fuel consumption in miles per gallon

8. }

members

Template

EXAMPLE 1 OF CREATING AND REFERENCING AN OBJECT

Page 5: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

5

9. class VehicleDemo {

10. public static void main(String args[]) {

11. Vehicle minivan = new Vehicle();

12. int range;

14. // assign values to fields in minivan

15. minivan.passengers = 7;

16. minivan.fuelcap = 16;

17. minivan.mpg = 21;

18. // compute the range assuming a full tank of gas

19. range = minivan.fuelcap * minivan.mpg;

20. System.out.println("Minivan can carry " + minivan.passengers +

21. " with a range of " + range);

22. }

23. }

reference

設計圖

instance

Page 6: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

6

EXAMPLE 2 OF CREATING AND REFERENCING AN OBJECT1. class Vehicle { 2. int passengers;3. int fuelcap;4. int mpg;5. }6. 7. class TwoVehicles { 8. public static void main(String args[]) { 9. Vehicle minivan = new Vehicle(); 10. Vehicle sportscar = new Vehicle(); 11. 12. int range1, range2;

13. // assign values to fields in minivan 14. minivan.passengers = 7; 15. minivan.fuelcap = 16; 16. minivan.mpg = 21;

minivan

sportscar

passengers7

feulcap16

mpg21

passengers2

feulcap14

mpg12

Page 7: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

7

1. // assign values to fields in sportscar 2. sportscar.passengers = 2; 3. sportscar.fuelcap = 14; 4. sportscar.mpg = 12; 5. 6. // compute the ranges assuming a full tank of gas 7. range1 = minivan.fuelcap * minivan.mpg; 8. range2 = sportscar.fuelcap * sportscar.mpg; 9. 10. System.out.println("Minivan can carry " + minivan.passengers + 11. " with a range of " + range1); 12. 13. System.out.println("Sportscar can carry " + sportscar.passengers + 14. " with a range of " + range2); 15. } 16. }

Page 8: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

8

METHOD: 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.

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.

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

Page 9: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

9

ADDING A PARAMETERIZED METHOD TO VEHICLE

1. class Vehicle { 2. int passengers; 3. int fuelcap; 4. int mpg; 5. 6. int range() { 7. return mpg * fuelcap; 8. } 9. 10. 11. double fuelneeded(int miles) { 12. return (double) miles / mpg; 13. } 14. }

parameter

Page 10: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

10

1. class CompFuel { 2. public static void main(String args[]) { 3. Vehicle minivan = new Vehicle(); 4. Vehicle sportscar = new Vehicle(); 5. double gallons; 6. int dist = 252; 7. 8. minivan.passengers = 7; 9. minivan.fuelcap = 16; 10. minivan.mpg = 21; 11. 12. sportscar.passengers = 2; 13. sportscar.fuelcap = 14; 14. sportscar.mpg = 12; 15. 16. gallons = minivan.fuelneeded(dist);17. System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel."); 18. gallons = sportscar.fuelneeded(dist); 19. System.out.println("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel."); 20. } 21. }

argument

Page 11: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

11

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 If there is a constructor defined, no default constructor will be added by

javac. The name of a 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.

Page 12: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

12

EXAMPLE OF USING CONSTRUCTORS// A simple constructor. class MyClass { int x; MyClass() { x = 10; } } class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); System.out.println(t1.x + " " + t2.x); } }

10 10

Page 13: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

13

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 t1 = new MyClass(); MyClass t2 = new MyClass(5); MyClass t3 = new MyClass(4, 3 + 4); System.out.println(t1.x + " " + t2.x + " " + t3.x); }}

0 5 4

Page 14: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

14

EXERCISE 1 METHOD WITH CONSTRUCTOR

Ex1a. 計算華氏溫度 class DegreeInC {

int temperature;

DegreeInC(int t) { … }

double convert() { … }

}

Ex1b. 計算 [a, b] 區間中整數的總和class Region {

int left_margin;

int right_margin;

Region(int l, int r) { … }

int sum() { … }

}

Page 15: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

15

EXERCISE 2

Complete the count method which returns the number of elements in array A that is less than the integer n.

class Ex8{

public static void main(String args[]) {

Scanner scn = new Scanner(System.in);

int A[] = { 6, 7, 7, 3, 6, 7, 4 };

int n = scn.nextInt();

Problem p = new Problem ();

System.out.println(p.count(n, A));

}

}

class Problem {

( 待完成 )

}

Page 16: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

16

ENCAPSULATION AND INFORMATION HIDING

Java provides class construct to support encapsulation and information hiding.

Using class construct, programmers can use the data and services provided by another class to complete tasks without knowing the implementation details of the class. Remember that you have use System, PrintStream, Integer

and Scanner classes in J2SDK without knowing their implementation details.

Page 17: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

17

MORE REQUIREMENT FOR ENCAPSULATION AND INFORMATION HIDING

Thinking about the following scenario. You are about to design a class Clock to represent clocks

which provide the functions of setting and displaying date and time, and also setting the alarm. How to prevent a user from setting a illegal date and/or time, such as Feb. 30, 2013?

To complete your design, you need a mechanism to protect the fields from directly accessing by users and only allow users to access the fields through the methods in the same class. The values set to fields can be verified by the methods.

Java provides access modifiers to protect the members of a class.

Page 18: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

18

ACCESS MODIFIERS Java provides 3 access modifiers for declaring class members : public,

protected and private. Java provides 4 access modes.

Visible to everyone: using public Visible to the package and subclasses: using protected Visible to the package, but not subclasses: declared without any access modifier Visible to the class only: using private

When a member is declared with a access modifier, the access modifier must be the first keyword.

The ordering, based on the strength of restriction, of the 4 types of access modes from least to most is public, protected, default and private.

When you select a proper access modifier for a field, follow the principle of least privilege.

Since the scope of local variables and parameters is within the method which defines the variables, they cannot be declared with any access modifier.

Page 19: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

19

Java Program

ming

Spring. 2013

Modifier Same Class Same Package Subclass Universe

private Yes

default Yes Yes

protected Yes Yes Yes

public Yes Yes Yes Yes

Page 20: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

20

PACKAGES

In Java, a package means a group of functional related classes.

Packages are both an organizational and an access control feature. The access control feature will be discussed in later lecture.

A package is similar to a directory in Microsoft Windows. A package may contain packages and classes. A package and its sub-packages/classes are separated by

dot. A fully-qualified class name consists of all the package

names starting from the root, e.g. the fully qualified class name for System is java.lang.System.

Page 21: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

21

EXAMPLE OF USING PUBLIC AND PRIVATEclass data{

private int i=10;public int j=20;void display() {

System.out.println("a.i=" + i);}

}class App172{

public static void main(String[] args){

data a = new data();// system.out.println("a.i=" + a.i);a.display(); System.out.println("a.j=" + a.j);

}}

a.i=10a.j=20

app172.java:18: error: i has private access in data System.out.println("a.i=" + a.i); ^1 error

Page 22: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

22

EXAMPLE

class MyClass { private int alpha; public int beta; int gamma; // default access void setAlpha(int a) { alpha = a; } int getAlpha() { return alpha; } }

class AccessDemo { public static void main(String args[]) { MyClass ob = new MyClass(); ob.setAlpha(-99); System.out.println("ob.alpha is " + ob.getAlpha()); // ob.alpha = 10; // Wrong! alpha is private! ob.beta = 88; ob.gamma = 99; } }

ob.alpha is -99

Page 23: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

23

EXAMPLEclass MyClass { public int alpha = 1; protected int beta =2; int gamma =3; private int lambda = 4;

void setLambda(int a) { lambda = a * alpha + beta / gamma; } int getLambda() { return lambda; }

}class AccessDemo2 { public static void main(String args[]) { MyClass ob = new MyClass(); ob.setLambda(-99); System.out.println("ob Lambda is " + ob.getLambda()); ob.alpha = 77;; ob.beta = 88; ob.gamma = 99; }}

ob Lambda is -99

Modifier Same Class

Same Package Subclass Universe

private Yes

default Yes Yes

protected Yes Yes Yes

public Yes Yes Yes Yes

Page 24: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

24

GETTERS AND SETTERS

By convention, fields should be declared as private and accessed through methods.

The method used to set the value of a field is called setter. The name of a setter, by convention and JavaBeans

specification, is beginning with “set” and then the field name (capitalized the first character of the field name). Example: setLambda()

The method used to get the value of a field is called getter.

The name of a getter, by convention and JavaBeans specification, is beginning with “get” and then the field name (capitalized the first character of the field name). Example: getLambda()

Page 25: L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length

EXERCISE 3

Create a class called Test. 利用 Test 來維護一個陣列 .

class Test{ private int data[]; Test() { … } public void setData(int index, int value) { … } public int getData(int index) { … }}

2 hr

public void setData(int index, int value)

public int getData(int index)

API example

http://docs.oracle.com/javase/7/docs/api/25