1 / 38

Inheritance

Inheritance. Motivation Code reuse Conceptual modeling. How to do inheritance in Java. Syntax class 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!

lavender
Download Presentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Inheritance • Motivation • Code reuse • Conceptual modeling

  2. How to do inheritance in Java • Syntax class A extends B{ … } • Class A automaticallyinherits 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(…)

  3. 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; } }

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

  5. Inheritance class architecture Student Account Undergrad Postgrad Checking Account Savings Account Master’s PhD

  6. “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)

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

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

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

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

  11. 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();

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

  13. 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 #1 calls #2 calls #1 calls #3

  14. Accessing Superclass Members public 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(); } } Output: Printed in Superclass. Printed in Subclass

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

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

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

  18. equivalent Q: What if all constructors in the superclass require parameters?? Constructors and Inheritance • the correct solution: public class SavingsAccount extends BankAccount{ private double interestRate; public SavingsAccount(){ interestRate = 0; } } 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; } } Explicitly calling the constructor of the superclass A: Compilation error

  19. 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; } … }

  20. class Student { // instance attributes private String name; private long number; //constructor public Student(String aName, long aNumber){ name = aName; number = aNumber; } // instance methods public void setName(String aName){ name = aName; } public String getName(){ return name; } public void setNumber(long aNumber){ number = aNumber; } public long getNumber(){ return number; } public String toString(){ return "Student[name=" + name + ",number=" + number + "]"; } } • class Undergrad extends Student{ • // instance attributes • private String major; • private int year; • //constructor • public Undergrad(String aName, long aNumber, String aMajor, int aYear){ • super (aName, aNumber); • setMajor (aMajor); • setYear(aYear); • } • // new methods • public void setMajor(String aMajor){ • major = aMajor; • } • public String getMajor(){ • return major; • } • public void setYear(int aYear){ • year = aYear; • } • public int getYear(){ • return year; • } • // overriding the base class toString() • public String toString(){ • return "Undergrad[name=" + getName() + • ",number=" + getNumber() + " • ,major=" + major + • ",year=" + year + "]"; • } • } Overriding

  21. 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()); } } Output: s1 is John Student[name=John,number=202123456] s2 is Mary s2 is in year 1 Undergrad[name=Mary Ellen,number=201234567,major=ITEC,year=1]

  22. 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 + "]"; }

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

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

  25. Example 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 main Undergrad u = new Undergrad("John", 201234567, "ITEC", 1);

  26. Multiple Layers of Inheritance • Each ancestor’s constructor is called in turn public 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; }

  27. Converting Between Subclass and Superclass Types • Converting a subclass type to a superclass type SavingsAccount savings = new SavingsAccount(5); BankAccount anAccount = savings; Object anObject = savings; (All references can be converted to the type Object) • savings, anAccount, andanObjectall refer to the same object of typeSavingsAccount • anAccount knows less about the SavingsAccount object • E.g., only methods defined in BankAccount are accessible • anObject knows even less

  28. 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 reuse public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } can pass to it any argument of type BankAccount or its subclasses

  29. Converting superclass type reference to subclass type reference • Casting SavingsAccount savings = (SavingsAccount) anAccount; This can be dangerous: anAccount is not necessarily a reference to a SavingsAccount object! • Use instanceof to protect against bad casts if (anAccount instanceof SavingsAccount) { SavingsAccount savings = (SavingsAccount) anAccount; }

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

  31. 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; } ... }

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

  33. 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”);

  34. 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 method Coin value name public class Coin { . . . public boolean equals(Object otherObject) { Coin other = (Coin) otherObject; return name.equals(other.getName()) && value.equals(other.getValue()); } . . . }

  35. 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); } }

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

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

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

More Related