Presentation is loading. Please wait.

Presentation is loading. Please wait.

2015 Spring Content Class method [review] Access control

Similar presentations


Presentation on theme: "2015 Spring Content Class method [review] Access control"— Presentation transcript:

0 Lec. 06: Class Details

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

2 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

3 Example 1 of creating and referencing an object
/* A program that uses the Vehicle class. Call this file VehicleDemo.java */ class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg; // fuel consumption in miles per gallon } Template members

4 public static void main(String args[]) {
class VehicleDemo { public static void main(String args[]) { Vehicle minivan = new Vehicle(); int range; // assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; // compute the range assuming a full tank of gas range = minivan.fuelcap * minivan.mpg; System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range); } 設計圖 reference instance

5 Example 2 of creating and referencing an object
minivan passengers class Vehicle { int passengers; int fuelcap; int mpg; } class TwoVehicles { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); int range1, range2; // assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; 7 feulcap 16 mpg 21 sportscar passengers 2 feulcap 14 mpg 12

6 // assign values to fields in sportscar
sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; // compute the ranges assuming a full tank of gas range1 = minivan.fuelcap * minivan.mpg; range2 = sportscar.fuelcap * sportscar.mpg; System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range1); System.out.println("Sportscar can carry " + sportscar.passengers + " with a range of " + range2); }

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

8 Adding a parameterized method to vehicle
class Vehicle { int passengers; int fuelcap; int mpg; int range() { return mpg * fuelcap; } double fuelneeded(int miles) { return (double) miles / mpg; parameter

9 class CompFuel { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); double gallons; int dist = 252; minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; gallons = minivan.fuelneeded(dist); System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel."); gallons = sportscar.fuelneeded(dist); System.out.println("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel."); } argument

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

11 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

12 Example 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);

13 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() { … }

14 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 { (待完成)

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

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

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

18 Modifier Same Class Same Package Subclass Universe private Yes default protected public

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

20 Example 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); app172.java:18: error: i has private access in data System.out.println("a.i=" + a.i); ^ 1 error a.i=10 a.j=20

21 Example ♥ class AccessDemo {
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

22 Example Modifier Same Class Same Package Subclass Universe private Yes default protected public 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; ob Lambda is -99

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

24 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) API example public void setData(int index, int value) public int getData(int index) 2 hr


Download ppt "2015 Spring Content Class method [review] Access control"

Similar presentations


Ads by Google