30.12.2013 Views

Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...

Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...

Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CS151 Object-Oriented Design<br />

Dr. Kim<br />

• You can use a subclass object B whenever a super class object A is expected because B is<br />

A.<br />

• Example: Can set e to Manager reference because a manager is an employee.<br />

public void someMethod(Employee e)<br />

{ System.out.println("salary=" + e.getSalary());}<br />

• Polymorphism: Correct getSalary method is invoked based on the actual object the<br />

variable e references not the type of the variable e.<br />

<strong>6.1</strong>.5 Invoking Superclass Methods<br />

• Can't access private fields of superclass<br />

public class Manager extends Employee<br />

{<br />

public double getSalary()<br />

{<br />

return salary + bonus; // ERROR--private field<br />

}<br />

...<br />

}<br />

• Be careful when calling superclass method<br />

public double getSalary()<br />

{<br />

return getSalary() + bonus; // ERROR --recursive call<br />

}<br />

• Use super keyword<br />

public double getSalary()<br />

{<br />

return super.getSalary() + bonus;<br />

}<br />

• super suppresses the polymorphic call mechanism <strong>and</strong> forces the superclass method to be<br />

called instead. It calls an appropriate method of the closest class in the hierarchy.<br />

<strong>6.1</strong>.6 Invoking Superclass Constructors<br />

4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!