Inheritance Motivation –Code reuse –Conceptual modeling.

38
Inheritance • Motivation Code reuse Conceptual modeling

Transcript of Inheritance Motivation –Code reuse –Conceptual modeling.

Page 1: Inheritance Motivation –Code reuse –Conceptual modeling.

Inheritance

• Motivation– Code reuse

– Conceptual modeling

Page 2: Inheritance Motivation –Code reuse –Conceptual modeling.

How to do inheritance in Java

• Syntaxclass A extends B{

}

• Class A automatically inherits all members (methods and attributes) of class B– Only need to specify new methods and attributes in the subclass!

– Constructor is not inherited (because it’s not a method)• super(…)

Page 3: Inheritance Motivation –Code reuse –Conceptual modeling.

public class Account { protected double balance; public Account( double amount ) { balance = amount; } public Account() { balance = 0.0; } public void deposit( double amount ) { balance += amount; } public double withdraw( double amount ) { if (balance >= amount) { balance -= amount; return amount; } else return 0.0; } public double getbalance() { return balance; } }

public class InterestBearingAccount extends Account { private static double default_interest = 7.95; private double interest_rate; public InterestBearingAccount( double amount, double interest) { balance = amount; interest_rate = interest; } public InterestBearingAccount( double amount ) { balance = amount; interest_rate = default_interest; } public void add_monthly_interest() { // Add interest to our account balance = balance + (balance * interest_rate / 100) / 12; } }

Page 4: Inheritance Motivation –Code reuse –Conceptual modeling.

Superclass and Subclass

• general vs. specialized• subclass is also called derived class, extended class, or

child class• superclass is also called base class or parent class

Page 5: Inheritance Motivation –Code reuse –Conceptual modeling.

Inheritance class architecture

Undergrad Postgrad

Account

Checking Account

Student

Savings Account

PhDMaster’s

Page 6: Inheritance Motivation –Code reuse –Conceptual modeling.

“Is a” Relationship

• An Undergrad “is a” Student• But not all inheritances are intended for “is a” type

of relationship– Some are simply expanding information

• Point (x, y) Circle (x, y, r) Cylinder (x, y, r, h)

Page 7: Inheritance Motivation –Code reuse –Conceptual modeling.

Java Class Hierarchy

• Every class is a subclass of Object!– Implicitly extends the Object class

A class has exactly one direct superclass (except for the Object class)

Page 8: Inheritance Motivation –Code reuse –Conceptual modeling.

What You Can Do in a Subclass

• All fields are inherited from the superclass. • You can declare a field in the subclass with the same name

as the one in the superclass, thus hiding/shadowing it (not recommended).

• You can declare new fields in the subclass that are not in the superclass.

• The inherited methods can be used directly as they are. • You can write a new instance method in the subclass that

has the same signature as the one in the superclass, thus overriding it.

• You can declare new methods in the subclass that are not in the superclass.

• You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

Page 9: Inheritance Motivation –Code reuse –Conceptual modeling.

Inheritance and Attributes

• Private attributes– inherited, but not directly accessible

– only accessible through public methods of the superclass

• Redefining an attribute in the subclass– The attribute inherited from the superclass is not replaced!

• Stored in different memory areas

– the subclass attribute will hide/shadow the one defined in the superclass

Page 10: Inheritance Motivation –Code reuse –Conceptual modeling.

Avoid Shadowing Instance Attributes

public class CheckingAccount extends BankAccount { … public void deposit(double amount) { transactionCount++; balance = balance + amount; // ERROR!! }}

How about adding an instance attribute balance to the subclass? public class CheckingAccount extends BankAccount { … // Shadowing the superclass attribute : don’t private double balance; public void deposit(double amount) { transactionCount++; balance = balance + amount; }}

Page 11: Inheritance Motivation –Code reuse –Conceptual modeling.

Example

public class Parent{ ... private int att; public setAtt(int n){ att = n; } }public class Offspring extends Parent{ private int att; public void meth(){ att = 4; // sets Offspring’s att setAtt(3);// sets Parent’s att }} // in main Offspring o = new Offspring(); o.meth();

Page 12: Inheritance Motivation –Code reuse –Conceptual modeling.

Methods: Overriding vs. Overloading

• Overriding– A method in the subclass which has the same signature and

return type as a method in the superclass

– The method in the subclass overrides the method inherited from the superclass

– The method from superclass is still available through super

• Overloading– Several methods with the same name in the same class

– Only possible when the signatures of methods are different

– Signature• the combination of the method's name along with the number

and types of the parameters (and their order).

Page 13: Inheritance Motivation –Code reuse –Conceptual modeling.

Example

public class Parent { public void meth() // #1 { ... } public void meth(int n) // #2 { ... } ...}public class Offspring extends Parent { public void meth(int n) // #3 { ... } ...}...// in main Parent o1 = new Parent(); Offspring o2 = new Offspring(); o1.meth(); o1.meth(31); o2.meth(); o2.meth(29);

Overloading

Overriding #2

calls #1calls #2calls #1calls #3

Page 14: Inheritance Motivation –Code reuse –Conceptual modeling.

Accessing Superclass Memberspublic class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); }}

public class Subclass extends Superclass { public void printMethod() { //overrides printMethod in Superclass super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } }

Printed in Superclass. Printed in Subclass

Output:

Page 15: Inheritance Motivation –Code reuse –Conceptual modeling.

Failing to Invoke the Superclass Method

public class Subclass extends Superclass { … public void printMethod() { printMethod(); // should be super.printMethod() !! System.out.println("Printed in Subclass"); }}

Calling printMethod() == calling this.printMethod()

public void withdraw(double amount){ transactionCount++; withdraw(amount); // should be super.widthdraw(amount)!}

Don’t forget to call the superclass method when necessary

Page 16: Inheritance Motivation –Code reuse –Conceptual modeling.

protected Members

• protected access members– Between public and private in protection

– Accessed only by• Superclass methods

• Subclass methods

• Methods of classes in same package

– package access

– allows the derived classes to directly access those protected attributes (no need to use methods to access them)

– if the superclass’s attribute is protected, and there is another derived class attribute with the same name (bad idea !), you can refer to the base class attribute as super.attribute.

Page 17: Inheritance Motivation –Code reuse –Conceptual modeling.

Constructors and Inheritance

public class BankAccount {

private double balance;

public BankAccount(){ balance = 0; }

public BankAccount(double initialBalance){

balance = initialBalance;

}

}

public class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

interestRate = 0;

balance = 0;

}

}

Wrong! The subclass doesn’t have access to this attribute

Page 18: Inheritance Motivation –Code reuse –Conceptual modeling.

Constructors and Inheritance

public class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

interestRate = 0;

}

}

• the correct solution:

the default constructor from the superclass with 0 parameters will be called automatically.

public class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

super();

interestRate = 0;

}

}

equivalent

Explicitly calling the constructor of the superclass

Q: What if all constructors in the superclass require parameters??

A: Compilation error

Page 19: Inheritance Motivation –Code reuse –Conceptual modeling.

Constructors and Inheritance

public class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

super();

interestRate = 0;

}

//a constructor with two parameters

public SavingsAccount(double initialBalance, double rate){

// call the 1 param constructor of the superclass explicitly

super(initialBalance);

interestRate = rate;

}

}

Page 20: Inheritance Motivation –Code reuse –Conceptual modeling.

1. class Student {2. // instance attributes3. private String name;4. private long number;

5. //constructor6. public Student(String aName, long

aNumber){7. name = aName;8. number = aNumber;9. }

10. // instance methods11. public void setName(String aName){ 12. name = aName;13. }14. public String getName(){ 15. return name;16. }17. public void setNumber(long aNumber){ 18. number = aNumber;19. }20. public long getNumber(){ 21. return number;22. }23. public String toString(){ 24. return "Student[name=" + name +

",number=" + number + "]";25. }26.}

1. class Undergrad extends Student{ 2. // instance attributes3. private String major;4. private int year;

5. //constructor6. public Undergrad(String aName, long

aNumber, String aMajor, int aYear){ 7. super (aName, aNumber);8. setMajor (aMajor);9. setYear(aYear);10. }11. // new methods12. public void setMajor(String aMajor){ 13. major = aMajor;14. }15. public String getMajor(){ 16. return major;17. }18. public void setYear(int aYear){ 19. year = aYear;20. }21. public int getYear(){ 22. return year;23. }24. // overriding the base class toString()25. public String toString(){ 26. return "Undergrad[name=" + getName() +

27. ",number=" + getNumber() + " 28. ,major=" + major +29. ",year=" + year + "]";30. }31.}

Overriding

Page 21: Inheritance Motivation –Code reuse –Conceptual modeling.

public class Inh1 { public static void main(String[] args){ Student s1 = new Student("John",202123456); System.out.println("s1 is " + s1.getName()); System.out.println(s1.toString()); Undergrad s2 = new Undergrad("Mary",201234567,"ITEC",1); System.out.println("s2 is "+s2.getName()); //inherited s2.setName("Mary Ellen"); //inherited System.out.println("s2 is in year " + s2.getYear()); //new method System.out.println(s2.toString()); }}

s1 is JohnStudent[name=John,number=202123456]s2 is Marys2 is in year 1Undergrad[name=Mary Ellen,number=201234567,major=ITEC,year=1]

Output:

Page 22: Inheritance Motivation –Code reuse –Conceptual modeling.

Note

• Another implementation of the subclass method toString(), which uses the base class toString(): public String toString(){

// call superclass’s method

String s = super.toString();

// make appropriate changes & return

s = s.substring(s.indexOf("["),s.length()-1);

return "Undergrad" + s + ",major=" + major + ",year=" + year + "]";

}

Page 23: Inheritance Motivation –Code reuse –Conceptual modeling.

The super Keyword

• super(…): calls the constructor of the superclass (0 or more parameters)

• super.aMethod(…): calls the method aMethod(…) from the superclass

• When used in a subclass constructor, super(…) must be the first statement of the constructor.

• super.aMethod(…) can be anywhere in any subclass method

Page 24: Inheritance Motivation –Code reuse –Conceptual modeling.

To summarize…

• The constructor(s) of the superclass can be called explicitly in the subclass constructor using super(…) (with 0 or more parameters)

• If superclass’s constructor is not called explicitly, super() will be called by default at the beginning of the subclass constructor.

Page 25: Inheritance Motivation –Code reuse –Conceptual modeling.

public class Student{ public Student() { name = "UNKNOWN"; number = -1; } public Student(String aName, long aNumber){ name = aName; number = aNumber; } ... private String name; private long number;}public class Undergrad extends Student{ public Undergrad(){ super(); // calls Student’s 0 args constructor major = "general"; year = 1; } public Undergrad(String aName, long aNumber, String aMajor, int aYear){ super(aName, aNumber); // calls Student’s 2 args constructor major = aMajor; year = aYear; } ... private String major; private int year;}// in mainUndergrad u = new Undergrad("John", 201234567, "ITEC", 1);

Example

Page 26: Inheritance Motivation –Code reuse –Conceptual modeling.

Multiple Layers of Inheritance

• Each ancestor’s constructor is called in turnpublic class PartTimeUndergrad extends Undergrad{

public PartTimeUndergrad(){

super(); // calls Undergrad’s 0 args constructor

courseLoad = 2.5;

}

public PartTimeUndergrad(String aName, long aNumber, String

aMajor, int aYear, double aLoad){

// calls Undergrad’s 4 args constructor

super(aName, aNumber, aMajor, aYear);

courseLoad = aLoad;

}

...

private double courseLoad;

}

Page 27: Inheritance Motivation –Code reuse –Conceptual modeling.

Converting Between Subclass and Superclass Types

• Converting a subclass type to a superclass typeSavingsAccount savings = new SavingsAccount(5);

BankAccount anAccount = savings;

Object anObject = savings;

(All references can be converted to the type Object)– savings, anAccount, and anObject all refer to the same

object of type SavingsAccount– anAccount knows less about the SavingsAccount object

• E.g., only methods defined in BankAccount are accessible

– anObject knows even less

Page 28: Inheritance Motivation –Code reuse –Conceptual modeling.

Converting subclass type reference to superclass type reference

• Difference between converting references and numerical conversion– Numerical: different representations, copies are made

• E.g., int i = 1; double d = i;

– References: the value of the reference stays the same: the memory address of the object. No copies of objects are made!

• Useful for code reusepublic void transfer(double amount, BankAccount other) {

withdraw(amount);

other.deposit(amount);

}

can pass to it any argument of type BankAccount or its subclasses

Page 29: Inheritance Motivation –Code reuse –Conceptual modeling.

Converting superclass type reference to subclass type reference

• CastingSavingsAccount savings = (SavingsAccount) anAccount;

This can be dangerous: anAccount is not necessarily a reference to a SavingsAccount object!

• Use instanceof to protect against bad castsif (anAccount instanceof SavingsAccount) {

SavingsAccount savings = (SavingsAccount) anAccount;

}

Page 30: Inheritance Motivation –Code reuse –Conceptual modeling.

Inheritance Example

• Define a method public double calculateFees(double courseload)for Student and Undergrad which returns the fees to be paid by the student depending on his/her course load. Suppose that for students generally, the fees are $800/course, and that for undergraduates, there is an additional incidental charge of $100 for first year studentsand $150 for students in later years.

Page 31: Inheritance Motivation –Code reuse –Conceptual modeling.

public class Student{

...

public double calculateFees(double courseload){

final double FEE_PER_COURSE = 800;

return FEE_PER_COURSE * courseload;

}

...

}

public class Undergrad extends Student{

...

// override Student’s calculateFees method

public double calculateFees(double courseload){

final double INCIDENTAL_FEE_Y1 = 100;

final double INCIDENTAL_FEE_Y_GT_1 = 150;

double fee = super.calculateFees(courseload);

if (year == 1)

fee = fee + INCIDENTAL_FEE_Y1;

else

fee = fee + INCIDENTAL_FEE_Y_GT_1;

return fee;

}

...

}

Page 32: Inheritance Motivation –Code reuse –Conceptual modeling.

// in main

Student s = new Student("Mary", 202345678);

System.out.println(s + " fees: " + s.calculateFees(4.5));

Undergrad u = new Undergrad("John", 201234567, "ITEC", 1);

System.out.println(u + " fees: " + u.calculateFees(4.5));

// The following will not COPY an object; it will just create // another reference to the same object

Student s1=u;

// s1 will only see the student part of u

Page 33: Inheritance Motivation –Code reuse –Conceptual modeling.

The Cosmic Superclass

• Every class in Java inherits from the Object class• Methods in the Object class

– String toString(): returns a string representation of the object

– boolean equals(Object anotherObject): tests whether the object equals another object

– Object clone(): makes a full copy of an object

• You can use the Object methods or, better, override them in your classes s1=s.clone();

if (s1.equals(s))

System.out.println(“The two objects are identical”);

Page 34: Inheritance Motivation –Code reuse –Conceptual modeling.

Example: Overriding the equals method

• Use the equals method to compare two objects by their contents– if (coin1.equals(coin2)) …

// if the contents are the same– Different from if (coin1 == coin2), which tests whether the two references

are to the same object.

• Implementing the equals methodpublic class Coin {

. . .

public boolean equals(Object otherObject) {

Coin other = (Coin) otherObject;

return name.equals(other.getName()) && value.equals(other.getValue());

}

. . .

}

Coin

value

name

Page 35: Inheritance Motivation –Code reuse –Conceptual modeling.

Applet (JApplet)

• Applets are Java programs embedded in Web pages– http://java.sun.com/applets/jdk/1.4/demo/applets/Clock/example1.

html (an example)

• Class Applet or JApplet has the methods init(), start(), stop() which will be called automatically. – When you inherit JApplet you can overwrite these methods for

specific scenarios. import java.applet.Applet;

import java.awt.*;

public class RectangleApplet extends Applet {

public void paint(Graphics g) {

Rectangle cerealBox = new Rectangle (5,10,20,30);

g.draw(cerealBox);

}

}

Page 36: Inheritance Motivation –Code reuse –Conceptual modeling.

final Methods and Classes

• In writing classes one has to keep in mind that future applications might be extending them through inheritance.

• Design decisions:– The class: Do you want others to define subclasses of this class?

– Attributes(fields): protected or private?

– Methods: Do you want the derived classes to override them?

• The final keyword– preventing others from extending this class or from overriding certain

methods– public final class String { . . .}: nobody can extend the String class– final methods:

public class SecureAccount extends BankAccount{ public final boolean checkPassword(String password){

. . .

} // nobody can override this method

}

Page 37: Inheritance Motivation –Code reuse –Conceptual modeling.

Abstract Classes

• Abstract classes– Too generic to define real objects, no good default methods

• TwoDimensionalShape• public void computeArea()

– Forcing the programmers of subclasses to implement this method• public abstract void computeArea();

– Objects of abstract classes cannot be instantiated– Provides superclass from which other classes may inherit

• Normally referred to as abstract superclasses

• Concrete classes– Classes from which objects are instantiated– Provide specifics for instantiating objects

• Square, Circle and Triangle

Page 38: Inheritance Motivation –Code reuse –Conceptual modeling.

Abstract Classes

• A class that defines an abstract method, or that inherits an abstract method without overriding it, must be declared as abstract.

• Can also declare classes with no abstract methods as abstract – preventing users from creating instances of that class

• Why abstract classes? – Forcing programmers to create subclasses

– Avoiding useless default methods in superclasses others may inherit by accident.