Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Lectures / lecture3_1

.pdf
Скачиваний:
36
Добавлен:
14.10.2016
Размер:
887.32 Кб
Скачать

Access Control: Good Practice

A good practice when working with fields is to make fields as inaccessible as possible, and provide clear intent for the use of fields through methods.

1package demo;

2public class Foo3 {

3private int result = 20;

4protected int getResult() { return result; }

5}

1package test;

2import demo.Foo3;

3public class Bar3 extends Foo3 {

4private int sum = 10;

5public void reportSum() {

6 sum += getResult();

7}

8}

Overriding Methods

Consider a requirement to provide a String that represents some details about the Employee class fields.

1public class Employee {

2private int empId;

3private String name;

4// ... other fields and methods

5public String getDetails () {

6

return "Employee id: " + empId +

7

" Employee name:" + name;

8}

9}

Overriding Methods

In the Manager class, by creating a method with the same signature as the method in the Employee class, you are overriding the getDetails method:

1public class Manager extends Employee {

2private String deptName;

3// ... other fields and methods

4public String getDetails () {

5

return super.getDetails () +

6

" Department: " + deptName;

7}

8}

A subclass can invoke a parent method by using the super keyword.

Invoking an Overridden Method

Using the previous examples of Employee and Manager:

Employee e = new Employee (101, "Jim Smith", "011-12-2345", 100_000.00);

Manager m = new Manager (102, "Joan Kern", "012-23-4567", 110_450.54, "Marketing");

System.out.println (e.getDetails());

System.out.println (m.getDetails());

– The correct getDetails method of each class is called:

Employee id: 101 Employee name: Jim Smith

Employee id: 102 Employee name: Joan Kern Department: Marketing

Accessibility of Overridden Methods

An overriding method must provide at least as much access as the overridden method in the parent class.

public class Employee {

//... other fields and methods public String getDetails() { ... }

}

public class Manager extends Employee { //... other fields and methods

private String getDetails() { //... } // Compile time error

}

Applying Polymorphism

Suppose that you are asked to create a new class that calculates a stock grant for employees based on their salary and their role (manager, engineer, or admin):

1public class EmployeeStockPlan {

2public int grantStock (Manager m) {

3 // perform a calculation for a Manager

4}

5public int grantStock (Engineer e) {

6 // perform a calculation for an Engineer

7 }

8 public int grantStock (Admin a) {

9 // perform a calculation for an Admin

10}

11//... one method per employee type

12}

Applying Polymorphism

A good practice is to pass parameters and write methods that use the most generic form of your object as possible.

public class EmployeeStockPlan { public int grantStock (Employee e) {

// perform a calculation based on Employee data

}

}

// In the application class

EmployeeStockPlan esp = new EmployeeStockPlan (): Manager m = new Manager ();

int stocksGranted = grantStock (m);

...

Applying Polymorphism

Adding a method to Employee allows EmployeeStockPlan to use polymorphism to calculate stock.

public class Employee {

protected int calculateStock() { return 10; }

}

public class Manager extends Employee {

public int calculateStock() { return 20; }

}

public class EmployeeStockPlan {

 

private float stockMultiplier;

// Calculated elsewhere

public int grantStock (Employee e) {

return (int)(stockMultipier * e.calculateStock());

}

}

Using the instanceof Keyword

The Java language provides the instanceof keyword to determine an object’s class type at run time.

1public class EmployeeRequisition {

2public boolean canHireEmployee(Employee e) {

3if (e instanceof Manager) {

4

return true;

5

} else {

6

return false;

7

}

8}

9}

Quiz

Suppose that you have an Account class with a withdraw() method, and a Checking class that extends Account that declares its own withdraw() method. What is the result of the following code fragment?

1Account acct = new Checking();

2acct.withdraw(100);

a.The compiler complains about line 1.

b.The compiler complains about line 2.

c.Runtime error: incompatible assignment (line 1)

d.The Account.withdraw() method executes.

e.The Checking.withdraw() method executes.

Соседние файлы в папке Lectures