chapter4inheritanceabstractclassinterface (1)

40
Chapter 4 Chapter 4 Inheritance ,Ab stract Class and interface Prepared by : Prepared by : Puan Robiah Puan Robiah Hamzah Hamzah

Upload: saya-wani

Post on 17-Nov-2015

2 views

Category:

Documents


0 download

DESCRIPTION

oriented programming

TRANSCRIPT

  • Chapter 4Inheritance ,Abstract Class and interfacePrepared by :Puan Robiah Hamzah

    *

  • ObjectivesDescribe encapsulation, polymorphism, and inheritance terminologyDevelop a subclass from a superclass through inheritanceOverriding method in the subclassAbstract class and interface.Summary

  • Inheritanceis-a relationshipSingle inheritance Subclass is derived from one existing class (superclass)Multiple inheritanceSubclass is derived from more than one superclassNot supported by JavaIn Java, a class can only extend the definition of one class

  • Inheritance (continued)General Syntax:

    modifier(s) class ClassName extends ExistingClassName modifier(s){ memberList}

  • Inheritance Hierarchy

  • Inheritance RulesThe modifier protected makes a data member or method visible and accessible to the instances of the class and the descendant classes. The private members of the superclass are private to the superclassThe subclass can directly access the public members of the superclassThe subclass can include additional data and/or method membersThe subclass can override, that is, redefine the public methods of the superclassHowever, this redefinition applies only to the objects of the subclass, not to the objects of the superclassAll data members of the superclass are also data members of the subclassSimilarly, the methods of the superclass (unless overridden) are also the methods of the subclassRemember Rule 1 when accessing a member of the superclass in the subclass

  • Inheritance (continued)To write a methods definition of a subclass, specify a call to the public method of the superclassIf subclass overrides public method of superclass, specify call to public method of superclass:

    super.MethodName(parameter list)If subclass does not override public method of superclass, specify call to public method of superclass:

    MethodName(parameter list)

  • The protected ModifierThe protected modifier can be applied on data and methods in a class. A protected data or a protected method in a public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package. private, default, protected, public

    private, none (if no modifier is used), protected, public

    Visibility increases

  • Visibility Modifiers

    public class C2 {

    C1 o = new C1();

    can access o.x;

    can access o.y;

    can access o.z;

    cannot access o.u;

    can invoke o.m();

    }

    public class C1 {

    public int x;

    protected int y;

    int z;

    private int u;

    protected void m() {

    }

    }

    public class C5 {

    C1 o = new C1();

    can access o.x;

    cannot access o.y;

    cannot access o.z;

    cannot access o.u;

    cannot invoke o.m();

    }

    package p1;

    public class C3

    extends C1 {

    can access x;

    can access y;

    can access z;

    cannot access u;

    can invoke m();

    }

    package p2;

    public class C4

    extends C1 {

    can access x;

    can access y;

    cannot access z;

    cannot access u;

    can invoke m();

    }

  • Accessibility Summary

    private

    -

    -

    protected

    Accessed

    from the

    same class

    -

    Modifier

    on members

    in a class

    default

    public

    Accessed

    from a different

    package

    -

    Accessed

    from a

    subclass

    -

    -

    Accessed

    from the

    same package

  • Are superclasss Constructor Inherited?No. They are not inherited.They are invoked explicitly or implicitly. Explicitly using the super keyword.The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:To call a superclass constructorTo call a superclass method

  • Inheritance-example

    Building# size : String# price :doubleHouse + House (no:int)+ displayHouseDetails( ) Inheritance hierarchyextends(isa)+ Building(size:String, price:double)

    - houseNo : int House is a Building..superclasssubclass

  • Inheritance

    Building# size:String# price:doubleHouse + House (HouseNo:int)+ displayHouseDetails( )extends(isa)+ Building( size:String, price:double )

    - houseNo:int

    public class Building { protected String size; protected double price; public Building(String size, double price) { this.size = size; this.price = price; }

    public class House extends Building { private int houseNo; public House(int houseNo) { super(100 X 90, 100000); this.houseNo = houseNo; }// super is used to call superclass constructor

  • Inheritance

    public class Building { protected String size; protected double price; public Building(String size, double price) { this.size = size; this.price = price; } }

    public class House extends Building { private int houseNo; public House(int houseNo) { super(100 X 90, 100000); this.houseNo = houseNo; }

    public void displayHouseDetails() { System.out.println( House no:+houseNo); System.out.println( Size:+size); System.out.println( Price:+price); } }

    public class Test { public static void main(String[] args) { House myHouse = new House(8); MyHouse.displayHouseDetails(); } }(1) (2) (1) and (2) : Execution flow between classes

  • Overriding Methods in the SuperclassA subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding.

  • Overriding vs. Overloading

    When you run Test class in (a), a.p(10) invokes the p(int i), display 10, Test class in (b), nothing is printed.

    (a)(b)

    public class Test {

    public static void main(String[] args) {

    A a = new A();

    a.p(10);

    }

    }

    class B {

    public void p(int i) {

    }

    }

    class A extends B {

    // This method overrides the method in B

    public void p(int i) {

    System.out.println(i);

    }

    }

    public class Test {

    public static void main(String[] args) {

    A a = new A();

    a.p(10);

    }

    }

    class B {

    public void p(int i) {

    }

    }

    class A extends B {

    // This method overloads the method in B

    public void p(double i) {

    System.out.println(i);

    }

    }

  • The toString() method in ObjectThe toString() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. public String toString() { return color: +color + and is filled: +filled;}You can also s.o.p(loan.toString() with s.o.p(loan)

  • Method overriding

    Circle# radius : doubleCylinder + Cylinder()+ Cylinder (radius:double, length:double)+ getLength() :double+ setLength(length:double):void+ findArea():double+ Circle()+ Cirle(radius:double)+ getRadius() : double+ setRadius(radius:double)+ findArea():double

    - length : double

    superclasssubclassOverriding findArea() in superclass

  • Method overridingpublic class Circle{ protected double radius; public Circle() { radius = 1.0; } public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public double setRadius(double radius) { this.radius = radius; } public double findArea() { return radius * radius * 3.14159; }}Circle.java

    Overloaded constructors// This method will be overrided in Cylinder class

  • Method overridingpublic class Cylinder extends Circle{ private double length; public Cylinder() { super(); length = 1.0; } public Cylinder(double radius,double length) { super(radius); this.length = length; } public double getLength() { return length; } public double setLength(double length) { this.length = length; } public double findArea() { return 2 * super.findArea()+ 2 * getRadius() * Math.PI * length; }}Formular 2 * circle area + cylinder body areaCylinder.java Note : Overriden method must have the same signature and return type as its superclass

    // Modified findArea()

  • Method overridingpublic class Test{ public static void main(String[] args) { Circle circle = new Circle(); circle.findArea(); // calls findArea() in Circle Cylinder cylinder = new Cylinder(3.0,5.0); cylinder.findArea(); // calls findArea() in Cylinder : : }} Eg :Test.java

  • PolymorphismPolymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchyFor example, if Cat and Dog are subclasses of Pet, then the following statements are valid:

    A variable of class X may not refer to an object from the superclass or sibling classes of X.

    Sibling classes are those that share the common ancestor class.

    For example, the following statements are invalid:Dog myDog = new Cat();Cat myCat = new Pet();

  • Abstract Superclasses and Abstract MethodsWhen we define a superclass, we often do not need to create any instances of the superclass.

  • Definition: Abstract ClassAn abstract class is a class defined with the modifier abstract ORthat contains an abstract method ORthat does not provide an implementation of an inherited abstract method

    An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body.Private methods and static methods may not be declared abstract.

    No instances can be created from an abstract class.

  • Case 1Student Must Be Undergraduate or Graduate

    If a student must be either an undergraduate or a graduate student, we only need instances of UndergraduateStudent or GraduateStudent.

    Therefore, we must define the Student class so that no instances may be created of it. To ensure this, Student class must be declared abstract.

    Let the ComputeCourseGrade() to be the abstract method of Student class

  • Case 2Student Does Not Have to Be Undergraduate or Graduate.In this case, we may design the Student class in one of two ways.We can make the Student class instantiable, ORWe can leave the Student class abstract and add a third subclass, OtherStudent, to handle a student who does not fall into the UndergraduateStudent or GraduateStudent categories.

  • Which Approach to Use ?The best approach depends on the particular situation.

    When considering design options, we can ask ourselves which approach allows easier modification and extension.

  • Solution to case 1 and 2 ?Could all of you draw the UML diagrams to show the class inheritance for case 1 and 2 ?In UML, the abstract class and method is written in italic.Just draw to reflect your understanding on abstract class and method Its ok to make mistake now but the later one will not be forgiven.. May be the next slide helps you to produce the correct UML diagram

  • Other example : The abstract Vehicle

    Vehicle+ Vehicle(int year , double price)+ DisplayVehicleDetails ( )Car Aeroplane+ Car(double cc)+ DisplayVehicleDetails ( )+ Aeroplane(int bilPassenger)+ DisplayVehicleDetails ( )

    abstract class abstract method( no implementation ) concrete method ( with implementation )extends(isa)

  • Lets program.. : Polymorphism and Abstract class

    Create an abstract class named Vehicle. Data member is manufacturedYear and price per unit. Method member is an abstract method named DisplayVehicleDetails().

    Derive two classes from the Vehicle class: Car which also contains a field for cc value and Aeroplane which contains a variable to hold the number of passengers allowable. Each of the subclass has the implementation of the polymorphic DisplayVehicleDetails() which will display the details of Car and Aeroplane objects.

    Write a simple program to allow the client code (eg: Test class) to create Car object and Aeroplane object. Assign them to variables of class Vehicle. Use these objects to call DisplayVehicleDetails() to display the detail of both Car an Aeroplane objects.

  • Solution

    public class Test{ public static void main(String[] args) { Vehicle ride1 = new Car(1.5); Vehicle ride2 = new Aeroplane(1000); // use polymorphism

    ride1.DisplayVehicleDetails(); ride2.DisplayVehicleDetails(); // call polymorphic method }}

    public abstract class Vehicle // Vehicle class is abstract class{ protected int manufacturedYear; protected double price; protected Vehicle(int year,double price) // Vehicle constructor { manufacturedYear = year; this.price = price; } public abstract void DisplayVehicleDetails( ); // abstract method

    }

    Filenames :Test.java (client code) Vehicle.java

  • Solution(cont)

    public class Car extends Vehicle{ protected double cc;

    public Car(double cc) // Car constructor { super(2006 , 100000.0); this.cc = cc; } public void DisplayVehicleDetails( ) // display Car details { System.out.println( Car details :\n); System.out.println( Year Manufactured : + manufacturedYear); System.out.println( Price : + price); System.out.println( CC : + cc); }}

    Filename :Car.java

  • public class Aeroplane extends Vehicle{ protected int billPassenger;

    public Aeroplane(int passenger) // Aeroplane constructor { super(1990 , 500000.0); billPassenger = passenger; }

    public void DisplayVehicleDetail() // display Aeroplane details { System.out.println( Aeroplane details :\n); System.out.println( Year Manufactured : + manufacturedYear); System.out.println( Price : + price); System.out.println( Bill passenger : + billPassenger); }}

    Filename :Aeroplane.java

  • Inheritance versus InterfaceThe Java interface is used to share common behavior (only method headers) among the instances of different classes.Inheritance is used to share common code (including both data members and methods) among the instances of related classes.In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code.If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B.

  • interfaceA java interface is a formal declaration in which all methods contains no implementation

    Many unrelated classes can implement the same interface

    A class can implement many unrelated interfaces

    Example of java class declaration using interface :

    public class Aeroplane implements Flyer{}

  • The Flyer example

    Flyer+ takeOff ( )+ land ( )+ fly ( )Aeroplane+ takeOff ( )+ land ( )+ fly ( )

    The Flyer interface and Aeroplane Implementation

    public interface Flyer{ public void takeOff ( ); public void land ( ); public void fly ( );}

    public class Aeroplane implements Flyer{ public void takeOff ( ) { } public void land( ) { } public void fly( ) { }} implements (is-a-kind-of)

  • The Flyer example

    Flyer+ takeOff + land ( )+ fly ( )Aeroplane+ takeOff ( )+ land ( )+ fly ( )

    Multiple implementations of the Flyer Interface

    Bird+ takeOff ( )+ land ( )+ fly ( )+ buildNest ( )+ layEggs ( )

    Superman+ takeOff ( )+ land ( )+ fly ( )+ leapBuilding ( )+ stopBullet ( ) implement (is-a-kind-of)

  • Use of interfacesWe can say Aeroplane is a Vehicle, and it can fly. A Bird is an animal, and it can fly. These examples show that a class can inherit from one class but also implement some interfaces.This is a solution for multiple inheritance which is NOT allowed in Java.The next slide shows the complete diagram on how interface simulate multiple inheritance

  • Inheritance and Implementation

    Flyer+ takeOff + land ( )+ fly ( )Aeroplane+ takeOff ( )+ land ( )+ fly ( )

    A mixture of Inheritance and Implementation

    Bird+ takeOff ( )+ land ( )+ fly ( )+ buildNest ( )+ layEggs ( )

    Superman+ takeOff ( )+ land ( )+ fly ( )+ leapBuilding ( )+ stopBullet ( )

    HomoSapien

    Animal+ eat ( )

    Vehicle

  • Summary Inheritance is-a relationshipAbstract class must apply method overridingAbstract modifier able to cover for class and methodInterface- share the common behavior only (method body)Inheritance able to share both common data member and methodsPolymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchyInterface using the is a kind of relationshipAbstract method MUST apply method overriding because abstract method only have method header at abstract class. The details is at concrete class.Inheritance able to use method overriding

    *

    A variable of class X may not refer to an object from the superclass or sibling classes of X.

    Sibling classes are those that share the common ancestor class.

    For example, the following statements are invalid:Dog myDog = new Cat();Cat myCat = new Pet();