Download presentation
Presentation is loading. Please wait.
Published byThomasina McKinney Modified over 9 years ago
1
L EC. 06: C LASS D ETAILS 0
2
2015 S PRING C ONTENT Class method [review] Access control Passing arguments Method overloading Variable-length Arguments [ 不測驗,可列補充教材 ] Recursion Using the keyword static Nested classes Shadowing 1
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 2
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. } 3 members Template E XAMPLE 1 OF CREATING AND REFERENCING AN OBJECT
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. } 4 reference 設計圖 instance
6
E XAMPLE 2 OF CREATING AND REFERENCING AN OBJECT 1. 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; 5 minivan sportscar passengers 7 feulcap 16 mpg 21 passengers 2 feulcap 14 mpg 12
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. } 6
8
M ETHOD : 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. 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. 7
9
A DDING 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. } 8 parameter
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. } 9 argument
11
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 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. 10
12
E XAMPLE 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); } 11 10
13
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 t1 = new MyClass(); MyClass t2 = new MyClass(5); MyClass t3 = new MyClass(4, 3 + 4); System.out.println(t1.x + " " + t2.x + " " + t3.x); } 12 0 5 4
14
E XERCISE 1 M ETHOD WITH C ONSTRUCTOR 13 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() { … } }
15
E XERCISE 2 14 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 { ( 待完成 ) }
16
E NCAPSULATION 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. 15
17
M ORE 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. 16
18
A CCESS 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. 17
19
Spring. 2013 18 Java Programming ModifierSame ClassSame PackageSubclassUniverse privateYes defaultYes protectedYes publicYes
20
P ACKAGES 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. 19
21
E XAMPLE OF USING PUBLIC AND PRIVATE class 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); } 20 a.i=10 a.j=20 app172.java:18: error: i has private access in data System.out.println("a.i=" + a.i); ^ 1 error
22
E XAMPLE class MyClass { private int alpha; public int beta; int gamma; // default access void setAlpha(int a) { alpha = a; } int getAlpha() { return alpha; } 21 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 ♥
23
E XAMPLE class 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; } 22 ob Lambda is -99 Modifier Same Class Same Package SubclassUniverse privateYes defaultYes protectedYes publicYes
24
G ETTERS 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() 23
25
E XERCISE 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/ 24
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.