Chapte r Thre e Inheritan ce u 1 0
What Is Inheritance? In the real world: we inherit traits from our motheran d father . We als o inherit traits from We our migh t grandmothe r, grandfathe r, an d ancestor s.have similar eyes, the same smile,A different height. But we are in many ways "derived" from our parents. In software: object inheritance is more well defined! Objects that are derived from other both object "resemble"their parent s by inheritin g stat e (fields ) an dbehavior (methods). 2 uu )
Contd .Inheritanc e is A fundament al featur e of object- orientedprogrammin g whic h enable s the programmer to write A class based on an already existing class. Th e already existin g clas s is calle d the paren t clas s, or orsuperclas s, and the ne w clas s is calle d the subclas s,derived class. Th e subclass inherits (reuse s) the no n private member s(methods and variables) of the its own members as well. superclass, and may define Inheritance extends.  When class b is a subcla uss o uf class a, we say b is implemented in java usin g the keywor d 3 )
Advantages Of Inheritance.Cod e reusabilit y:- inheritan ce automates the process of reusing the code of the superclasses in the subclasses.  With inheritance, an object can inherit its more general properties from its paren t object , and that save s th e redundanc y in programmin g. Cod e maintenan ce:- organizin g cod e int o hierarchic alclasses makes its maintenance and management easier. Implement ing OOP:- inheritance help s to impleme nt th ebasic oop philosophy to adapt computing to the problem and not the other way around, because entities (objects) in the real world are often organized into a hierarchy. 4 uu )
Inheritance TypesA. Single level inheritance:- inheritance in super class. which a class inherits from only one B. Multi- level inheritance: - inheritanc e in which a class inherits from a class which itself inherits from another class.Here a minimum of three classes is required. here two or more  C. Hierarchy inheritance:- inherits from one class. D. Multiple inheritance:- a more classes. classe s class inherits from two or This type of inheritance is not supported in java.  5 )
Dog Class public class Dog { private String name;private int fleas; public Dog(string n, int f) { name = fleas = n; f; } public public public String getName() { return name; } int getFleas() { return fleas; } void speak() { System.out.println("woof"); } } 6 uu )
CAT CLASSpublic class Cat { private string name; private int hairBalls; public Cat(string n, int name = n; hairballs = h; } h) { public public public String getName() { return name; } int getHairBalls() { return void speak() { hairballs; } System.out.println("meow"); } } 7 uu )
Problem: Code Duplication Dog and Cat have the name field and the getName method in common Classes often in common have a lot of state and behavio r Resul t: lot s of duplicate code! 8 uu )
Solution: Inheritance Inheritance allows you to write new classes that inherit from existing classes The existing class whose properties are inherited is called the "parent" or superclassThe new class that inherits the "child" or subclass Result: lots of code reuse! from the supe r clas s is calle d 9 uu )
using inheritance superclass subclass subclass 10 ) Dog int fleas int getFleas() void speak() uu Cat int hairballs int getHairballs() voidspeak() Animal String name String getName() Cat String name int hairballs String getName() int getHairballs() voidspeak() Dog String name int fleas String getName() int getFleas() void speak()
Animal Superclass public { class Animal private String name; public Animal(string n) { name = n; } public String getName() { return name; } } 11 uu )
Dog Subclass public class Dog extends Animal { private int fleas; public Dog(string n, int f) { super(n); // calls animal fleas = f; constructor } public int getFleas() return fleas; } { public void speak() { return System.out.println("woof"); } uu } 12 )
Cat Subclass public class Cat extends Animal { private int hairballs; public Cat(string n, int h) { super(n); // calls animal hairballs = h; constructor } public int getHairBalls() { return hairballs; } public void speak() { return System.out.println("meow"); } } 13 uu )
Inheritance Quiz 1 • What is the output of the following?Dog d Cat c = = new Dog("rover" 3); new Cat("kitty", 2); System.out.println(d.getName() + " has " + d.getFleas() + " fleas"); System.out.println(c.getName() + " has " + c.getHairBalls() + " hairballs"); rover has 3 fleas kitty has 2 hairballs 14 (Dog and Cat inherit the ge utN uame method from )
Inheritance Rules Us e the extends keyword to indicat e that one clas sinherits from another The subclass inherits all the nonprivate fields and methods of the superclass Use the super keyword in the subclas s constructor to cal lthe superclas s constructor 15 uu )
Subclass Constructor • The first thing a subclass constructor must do is call the superclass constructor. • This ensures that the superclass part of the object is constructed before the subclass part • If you do not call the superclass constructor with the super keyword, and the superclass has a constructor with no arguments, then that superclass 16 uu )
Implicit Supe r Constructor Call then this Beef subclass: public class Beef extends Food private double weight; public Beef(double w) { weight = w } } { if I have this food class: public class food { private boolean public food() { raw = true; } } raw; is equivalent to: public class Beef extends Food private double weight; public Beef(double w) { super(); weight = w { 17 } u}u )
Inheritance Quiz 2public class public A() } A { { System.out.println("I'm A"); } public class public B() } B { extends A { System.out.println("I'm B"); } public class public C() } C { extends B { System.out.println("I'm C"); } What does this print out? I'm I'm I'm A B CC x = new C(); 18 uu )
Overriding Methods When a method type signature as method is said to in a super class has the same name as and a method in the superclass, then the subclass override the method in the superclass.  During overriding a method the following takes place:  The new method overrides (and hides) the original method.  When you override a method, you can call the superclass's copy of the method by using the syntax super.method().  You can not do super.super. to back up two levels.  You canno t chang e the return type whe n overridin g impossibl e. a method, since this would make polymorphism uu )
class MyDerived extends { int y; MyBase class MyBase { private int public MyDerived(int { super(x); } public MyDerived(int { super(x); x) x; public MyBase(int { x) x, int y) this.x } = x; public { return } public { int getX() this.y } public { return } public { = y; x; int getY() void show() y; System.out.println("x=" } } + x); void show() super.show(); System.out.println("y = " + y); } 20 uu} )
Final Variables, Methods And Class es All methods and variables in subclasses. can be overridden by default  Use th e fin al keywor d member s to of preven t th e subclass es from overriding the Example: final th e superclas s. This method will not be overridden int num=10; public final void show() { System.out.println("x=" + } x);  It is also possible to define a class as final if we class not to be inherited.  Any attempt to inherit a final class will cause wan t th e an error 21 )
Abstract Classes An abstract method is a method that is declared without implementation . an Exampl e: abstract void display(); An abstrac t clas s is a clas s that is incomplet e, or to be considered incomplete. Only abstract classes may have abstract methods, that is ,  methods that are declared but not yet implemented and non abstract methods. An abstract class may or may not contain abstract methods. An abstract class is a class that cannot be instantiated, we   cannot create instances of uan uabstract 22 )
Contd. While using abstract classes:  We cannot use abstract classes directly. to instantiate objects  The abstract method of an abstract clas s mus t be defined in its subclass.  We cannot declare abstract constructors or abstrac tstatic methods.  Abstract classes can methods and one or have none, one or more abstrac tmore non abstract methods. 23 )
abstract class A { abstract void callme(); // abstract method void callmetoo() // Non-abstract method { System.out.println("This is a concrete method."); } } class B extends A { void callme() //Implementation of super class’s { abstract method System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { A A B ab;// possible ab1=new A(); b = new B(); // Is not correct b.callme(); b.callmetoo(); 24 uu} } )
Visibility Control (Access Level)  By using inheritance it is possible to inherit all members of the superclass being on the subclasses.  But it is also possible to restrict from outside the class. This s done the access of certain fields using access modifiers.  Classes can contain fields and method s of four different access levels: A. private:- private variable s and method s are accessibl ewithin their own class (access only to the class itself) . B. Friendly access:- when no access modifier is specified, themembers’ are access only to classes in the same No access level is specified in this case. package . 25 )
Contd. C. protected:- makes the fields visible to all classes andsubclasses within th e sam e package and to all subclasses from other packages. D. Private protecte d:- make s th e fields visible in all subclasses regardless of what package they are in. These fields are not accessible by other classes in the same package. E. public:- These variables or methods have access to all classes everywhere. 26 such members. u ))
Programming Example A company has a list of employees. It asks you to provide a payroll sheet for all employees. Has extensive data (name, department, pay employees. amount, …) for all Different types engineer. You have an old employee class but need to of employee s – manager , enginee r, softwar e add very different data and methods for managers and engineers. Suppose someone wrote a nam e syste m, and already provided a legacy employee class.  The old employee class had a printData() method for eachemployee that only printed the name. We want to reuse it, and 27 uuprint pay info. )
Review PictureMessage passing "Main event loop"Encapsulation Employee e1 private: lastName firstName uu ) printData public … Main(…){ Employee e1…("Mary","Wang"); ... e1.printData(); // Prints Employee names. ... } 28
Employee class //This is a simpler super class class Employee { // Data private String firstName, lastName; // Constructor public Employee(String fName, String lName) { firstName= fName; lastName= lName; } // Method public void printData() { System.out.println(firstName + " " + lastName);} } 29 uu )
Inheritance Diagram Already written: Class Employee printData()firstName lastName is-a Class Engineer is-a Class Manager firstName lastName firstName lastName hoursWorked salary wagesprintData() getPay() printData() getPay() 30 You une uxt write: )
Engineer Class //A subclass derived from Employee class class Engineer extends Employee { private double wage; private double hoursWorked; public Engineer(String fName, String lName, double rate, double super(fName, lName); wage = rate; hoursWorked = hours; hours) { } public double getPay() { return wage * hoursWorked; } public void printData() { super.printData(); System.out.println("Weekly uu // PRINT NAME pay: Birr" + getPay(); 31 } } )
Manager Class //A subclass derived from Employee class class Manager extends Employee { private double salary; public Manager(String fName, super(fName, lName); salary = sal; } String lName, double sal){ public double getPay() { return salary; } public void printData() { super.printData(); System.out.println("Monthly salary: Birr" + salary);} } 32 uu )
Inheritance … Class Manager firstName lastName is-a Salary Class SalesManager firstName lastName Salary getPay u 33 u salesBonus ) printData printData getPay
Sales Manager Class //A subclass derived from Manager class class SalesManager extends Manager { private double salesBonus; commission. // Bonus Possible as // A SalesManager gets a constant public SalesManager(String fName, super(fName, lName, 1250.0); salesBonus = b; } salary String of $1250.0 lName, double b) { public double getPay() { return 1250.0; } public void printData() { super.printData(); System.out.println("Bonus Pay: uu $" + salesBonus; } 34 } )
Main Method public class PayRoll { public static void main(String[] args) { // Object creation and Initialization (Using constructors) Engineer fred Manager ann = new Engineer("Fred", "Smith", 12.0, 8.0); = new Manager("Ann", "Brown", 1500.0); SalesManager mary= new SalesManager("Mary", "Kate", 2000.0); // Polymorphism, or late binding Employee[] employees = new Employee[3]; employees[0]= employees[1]= employees[2]= fred; ann; mary; System.out.println(“===========================“); for (int i=0; i < 3; i++) employees[i].printData(); System.out.println(“===========================“); } uu 35 } )
Output from Main =========================== Fred Smith Weekly pay: $96.0 Ann Brown Monthly salary: $1500.0 Mary Barrett Monthly salary: $1250.0 Bonus: $2000.0 =========================== Note that we could not write: employees[i].getPay(); Method becaus e getPay( ) is no t a metho d of th e supercla ssEmployee. In contrast, printData() is a method of can find the appropriate version. Employee, so Java 36 )
Object Class All java classes implicitly inherit from java.lang.Object So every class you write will automatically have methods in object such as equals, and toString etc. We'll learn about the importanc e of som e of thes e methods inlater lectures . 37 uu )

Oop inheritance chapter 3

  • 1.
  • 2.
    What Is Inheritance? Inthe real world: we inherit traits from our motheran d father . We als o inherit traits from We our migh t grandmothe r, grandfathe r, an d ancestor s.have similar eyes, the same smile,A different height. But we are in many ways "derived" from our parents. In software: object inheritance is more well defined! Objects that are derived from other both object "resemble"their parent s by inheritin g stat e (fields ) an dbehavior (methods). 2 uu )
  • 3.
    Contd .Inheritanc e is A fundament al featur e ofobject- orientedprogrammin g whic h enable s the programmer to write A class based on an already existing class. Th e already existin g clas s is calle d the paren t clas s, or orsuperclas s, and the ne w clas s is calle d the subclas s,derived class. Th e subclass inherits (reuse s) the no n private member s(methods and variables) of the its own members as well. superclass, and may define Inheritance extends.  When class b is a subcla uss o uf class a, we say b is implemented in java usin g the keywor d 3 )
  • 4.
    Advantages Of Inheritance.Cod e reusabilit y:- inheritan ce automates the process of reusingthe code of the superclasses in the subclasses.  With inheritance, an object can inherit its more general properties from its paren t object , and that save s th e redundanc y in programmin g. Cod e maintenan ce:- organizin g cod e int o hierarchic alclasses makes its maintenance and management easier. Implement ing OOP:- inheritance help s to impleme nt th ebasic oop philosophy to adapt computing to the problem and not the other way around, because entities (objects) in the real world are often organized into a hierarchy. 4 uu )
  • 5.
    Inheritance TypesA. Single level inheritance:- inheritance in super class. which a classinherits from only one B. Multi- level inheritance: - inheritanc e in which a class inherits from a class which itself inherits from another class.Here a minimum of three classes is required. here two or more  C. Hierarchy inheritance:- inherits from one class. D. Multiple inheritance:- a more classes. classe s class inherits from two or This type of inheritance is not supported in java.  5 )
  • 6.
    Dog Class public class Dog{ private String name;private int fleas; public Dog(string n, int f) { name = fleas = n; f; } public public public String getName() { return name; } int getFleas() { return fleas; } void speak() { System.out.println("woof"); } } 6 uu )
  • 7.
    CAT CLASSpublic class Cat{ private string name; private int hairBalls; public Cat(string n, int name = n; hairballs = h; } h) { public public public String getName() { return name; } int getHairBalls() { return void speak() { hairballs; } System.out.println("meow"); } } 7 uu )
  • 8.
    Problem: Code Duplication Dog andCat have the name field and the getName method in common Classes often in common have a lot of state and behavio r Resul t: lot s of duplicate code! 8 uu )
  • 9.
    Solution: Inheritance Inheritance allows youto write new classes that inherit from existing classes The existing class whose properties are inherited is called the "parent" or superclassThe new class that inherits the "child" or subclass Result: lots of code reuse! from the supe r clas s is calle d 9 uu )
  • 10.
    using inheritance superclass subclass subclass 10 ) Dog int fleas int getFleas() voidspeak() uu Cat int hairballs int getHairballs() voidspeak() Animal String name String getName() Cat String name int hairballs String getName() int getHairballs() voidspeak() Dog String name int fleas String getName() int getFleas() void speak()
  • 11.
    Animal Superclass public { class Animal private Stringname; public Animal(string n) { name = n; } public String getName() { return name; } } 11 uu )
  • 12.
    Dog Subclass public class Dogextends Animal { private int fleas; public Dog(string n, int f) { super(n); // calls animal fleas = f; constructor } public int getFleas() return fleas; } { public void speak() { return System.out.println("woof"); } uu } 12 )
  • 13.
    Cat Subclass public class Catextends Animal { private int hairballs; public Cat(string n, int h) { super(n); // calls animal hairballs = h; constructor } public int getHairBalls() { return hairballs; } public void speak() { return System.out.println("meow"); } } 13 uu )
  • 14.
    Inheritance Quiz 1 • What isthe output of the following?Dog d Cat c = = new Dog("rover" 3); new Cat("kitty", 2); System.out.println(d.getName() + " has " + d.getFleas() + " fleas"); System.out.println(c.getName() + " has " + c.getHairBalls() + " hairballs"); rover has 3 fleas kitty has 2 hairballs 14 (Dog and Cat inherit the ge utN uame method from )
  • 15.
    Inheritance Rules Us e the extends keywordto indicat e that one clas sinherits from another The subclass inherits all the nonprivate fields and methods of the superclass Use the super keyword in the subclas s constructor to cal lthe superclas s constructor 15 uu )
  • 16.
    Subclass Constructor • The firstthing a subclass constructor must do is call the superclass constructor. • This ensures that the superclass part of the object is constructed before the subclass part • If you do not call the superclass constructor with the super keyword, and the superclass has a constructor with no arguments, then that superclass 16 uu )
  • 17.
    Implicit Supe r Constructor Call then thisBeef subclass: public class Beef extends Food private double weight; public Beef(double w) { weight = w } } { if I have this food class: public class food { private boolean public food() { raw = true; } } raw; is equivalent to: public class Beef extends Food private double weight; public Beef(double w) { super(); weight = w { 17 } u}u )
  • 18.
    Inheritance Quiz 2public class publicA() } A { { System.out.println("I'm A"); } public class public B() } B { extends A { System.out.println("I'm B"); } public class public C() } C { extends B { System.out.println("I'm C"); } What does this print out? I'm I'm I'm A B CC x = new C(); 18 uu )
  • 19.
    Overriding Methods When a method typesignature as method is said to in a super class has the same name as and a method in the superclass, then the subclass override the method in the superclass.  During overriding a method the following takes place:  The new method overrides (and hides) the original method.  When you override a method, you can call the superclass's copy of the method by using the syntax super.method().  You can not do super.super. to back up two levels.  You canno t chang e the return type whe n overridin g impossibl e. a method, since this would make polymorphism uu )
  • 20.
    class MyDerived extends { inty; MyBase class MyBase { private int public MyDerived(int { super(x); } public MyDerived(int { super(x); x) x; public MyBase(int { x) x, int y) this.x } = x; public { return } public { int getX() this.y } public { return } public { = y; x; int getY() void show() y; System.out.println("x=" } } + x); void show() super.show(); System.out.println("y = " + y); } 20 uu} )
  • 21.
    Final Variables, Methods And Class esAll methods and variables in subclasses. can be overridden by default  Use th e fin al keywor d member s to of preven t th e subclass es from overriding the Example: final th e superclas s. This method will not be overridden int num=10; public final void show() { System.out.println("x=" + } x);  It is also possible to define a class as final if we class not to be inherited.  Any attempt to inherit a final class will cause wan t th e an error 21 )
  • 22.
    Abstract Classes An abstractmethod is a method that is declared without implementation . an Exampl e: abstract void display(); An abstrac t clas s is a clas s that is incomplet e, or to be considered incomplete. Only abstract classes may have abstract methods, that is ,  methods that are declared but not yet implemented and non abstract methods. An abstract class may or may not contain abstract methods. An abstract class is a class that cannot be instantiated, we   cannot create instances of uan uabstract 22 )
  • 23.
    Contd. While using abstractclasses:  We cannot use abstract classes directly. to instantiate objects  The abstract method of an abstract clas s mus t be defined in its subclass.  We cannot declare abstract constructors or abstrac tstatic methods.  Abstract classes can methods and one or have none, one or more abstrac tmore non abstract methods. 23 )
  • 24.
    abstract class A { abstractvoid callme(); // abstract method void callmetoo() // Non-abstract method { System.out.println("This is a concrete method."); } } class B extends A { void callme() //Implementation of super class’s { abstract method System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { A A B ab;// possible ab1=new A(); b = new B(); // Is not correct b.callme(); b.callmetoo(); 24 uu} } )
  • 25.
    Visibility Control (AccessLevel)  By using inheritance it is possible to inherit all members of the superclass being on the subclasses.  But it is also possible to restrict from outside the class. This s done the access of certain fields using access modifiers.  Classes can contain fields and method s of four different access levels: A. private:- private variable s and method s are accessibl ewithin their own class (access only to the class itself) . B. Friendly access:- when no access modifier is specified, themembers’ are access only to classes in the same No access level is specified in this case. package . 25 )
  • 26.
    Contd. C. protected:- makesthe fields visible to all classes andsubclasses within th e sam e package and to all subclasses from other packages. D. Private protecte d:- make s th e fields visible in all subclasses regardless of what package they are in. These fields are not accessible by other classes in the same package. E. public:- These variables or methods have access to all classes everywhere. 26 such members. u ))
  • 27.
    Programming Example A companyhas a list of employees. It asks you to provide a payroll sheet for all employees. Has extensive data (name, department, pay employees. amount, …) for all Different types engineer. You have an old employee class but need to of employee s – manager , enginee r, softwar e add very different data and methods for managers and engineers. Suppose someone wrote a nam e syste m, and already provided a legacy employee class.  The old employee class had a printData() method for eachemployee that only printed the name. We want to reuse it, and 27 uuprint pay info. )
  • 28.
    Review PictureMessage passing "Mainevent loop"Encapsulation Employee e1 private: lastName firstName uu ) printData public … Main(…){ Employee e1…("Mary","Wang"); ... e1.printData(); // Prints Employee names. ... } 28
  • 29.
    Employee class //This is asimpler super class class Employee { // Data private String firstName, lastName; // Constructor public Employee(String fName, String lName) { firstName= fName; lastName= lName; } // Method public void printData() { System.out.println(firstName + " " + lastName);} } 29 uu )
  • 30.
    Inheritance Diagram Already written: Class EmployeeprintData()firstName lastName is-a Class Engineer is-a Class Manager firstName lastName firstName lastName hoursWorked salary wagesprintData() getPay() printData() getPay() 30 You une uxt write: )
  • 31.
    Engineer Class //A subclassderived from Employee class class Engineer extends Employee { private double wage; private double hoursWorked; public Engineer(String fName, String lName, double rate, double super(fName, lName); wage = rate; hoursWorked = hours; hours) { } public double getPay() { return wage * hoursWorked; } public void printData() { super.printData(); System.out.println("Weekly uu // PRINT NAME pay: Birr" + getPay(); 31 } } )
  • 32.
    Manager Class //A subclass derivedfrom Employee class class Manager extends Employee { private double salary; public Manager(String fName, super(fName, lName); salary = sal; } String lName, double sal){ public double getPay() { return salary; } public void printData() { super.printData(); System.out.println("Monthly salary: Birr" + salary);} } 32 uu )
  • 33.
  • 34.
    Sales Manager Class //A subclassderived from Manager class class SalesManager extends Manager { private double salesBonus; commission. // Bonus Possible as // A SalesManager gets a constant public SalesManager(String fName, super(fName, lName, 1250.0); salesBonus = b; } salary String of $1250.0 lName, double b) { public double getPay() { return 1250.0; } public void printData() { super.printData(); System.out.println("Bonus Pay: uu $" + salesBonus; } 34 } )
  • 35.
    Main Method public class PayRoll{ public static void main(String[] args) { // Object creation and Initialization (Using constructors) Engineer fred Manager ann = new Engineer("Fred", "Smith", 12.0, 8.0); = new Manager("Ann", "Brown", 1500.0); SalesManager mary= new SalesManager("Mary", "Kate", 2000.0); // Polymorphism, or late binding Employee[] employees = new Employee[3]; employees[0]= employees[1]= employees[2]= fred; ann; mary; System.out.println(“===========================“); for (int i=0; i < 3; i++) employees[i].printData(); System.out.println(“===========================“); } uu 35 } )
  • 36.
    Output from Main =========================== FredSmith Weekly pay: $96.0 Ann Brown Monthly salary: $1500.0 Mary Barrett Monthly salary: $1250.0 Bonus: $2000.0 =========================== Note that we could not write: employees[i].getPay(); Method becaus e getPay( ) is no t a metho d of th e supercla ssEmployee. In contrast, printData() is a method of can find the appropriate version. Employee, so Java 36 )
  • 37.
    Object Class All javaclasses implicitly inherit from java.lang.Object So every class you write will automatically have methods in object such as equals, and toString etc. We'll learn about the importanc e of som e of thes e methods inlater lectures . 37 uu )