Inheritance - PowerPoint PPT Presentation

1 / 54
About This Presentation
Title:

Inheritance

Description:

Car is a vehicle, PickUpTruck is a Truck. has a relationship (composed-of) Examples: Car has a wheel. Inheritance ... A class which must be extended to be used ... – PowerPoint PPT presentation

Number of Views:23
Avg rating:3.0/5.0
Slides: 55
Provided by: supp9
Category:

less

Transcript and Presenter's Notes

Title: Inheritance


1
Chapter 4
  • Inheritance

2
Two Relations
  • is-a relationship
  • Examples
  • Car is a vehicle,
  • PickUpTruck is a Truck.
  • has a relationship (composed-of)
  • Examples
  • Car has a wheel

3
Inheritance
  • Inheritance
  • Used to model the IS-A relationship
  • Used to reuse code among related classes
  • Containment
  • Used to model the has-a relationship

4
Inheritance Mechanism
  • class Base
  • int n
  • public Base() n1
  • class Derived extends Base
  • int n
  • public Derived() n10
  • public int getValue() return n
  • To define a subclass keyword extends
  • class FullName extends Name
  • Think about the memory layout with inheritance.
  • What is the memory layout without extends Base
    statement?

5

Example 1 Inheritance
  • class Base
  • int n
  • public Base() n1
  • class Derived
  • int n
  • public Derived() n10
  • public int getValue() return n

6
Example 1 Inheritance
  • public class TestInheritance
  • public static void main(String args)
  • Base b new Base()
  • Derived d1 new Derived()
  • System.out.println("base value "b.n)
  • System.out.println("derived value "d1.n)
  • System.out.println("derived value
    "d1.getValue())

7
Example 2 Inheritance
  • class Base
  • int n
  • public Base() n1
  • class Derived extends Base
  • int n
  • public Derived() n10
  • public int getValue() return n

8
Example 2 Inheritance
  • public class TestInheritance
  • public static void main(String args)
  • Base b new Base()
  • Derived d2 new Derived()
  • System.out.println("base value "b.n)
  • System.out.println("derived value "d2.n)
  • System.out.println("derived value
    "d2.getValue())
  • Example 1 and Example 2 has the same output, but
    the memory layouts of Object d1 and d2 are
    different.

9
Example 3 Inheritance
  • class Base
  • int n
  • public Base() n1
  • class Derived extends Base
  • int n
  • public Derived() n10
  • public int getValue1() return n
  • public int getValue2() return super.n
  • Super key word allows you to access members of
    Base class

10
Example 3 Inheritance
  • public class TestInheritance
  • public static void main(String args)
  • Base b new Base()
  • Derived d new Derived()
  • System.out.println("base value "b.n)
  • System.out.println("derived value "d.n)
  • System.out.println("derived value
    "d.getValue1())
  • System.out.println("derived value
    "d.getValue2())

11
Base Class Initialization Implicit Method 1
  • class Base
  • int n
  • Base() n 1
  • class Derived extends Base
  • int n
  • public Derived() n10
  • The default constructor Base() is called before
    line 4 is executed.
  • If the user-defined default constructor Base() is
    not given, a system-defined default constructor
    is used.

12
Base Class Initialization Implicit Method 2
  • class Base
  • int n
  • Base(int nn) n nn
  • class Derived extends Base
  • int n
  • public Derived() n10
  • Can you find what is wrong with this example?

13
Base Class Initialization Explicit Method
  • class Base
  • int n
  • Base() n 0
  • Base(int n) this.n n
  • class Derived extends Base
  • int n
  • public Derived() super(-1) n10
  • public int getValue1() return n
  • public int getValue2() return super.n
  • Using super() key word, you can explicit choose
    which super class constructor you want to use.

14
  1. class Base
  2. int n
  3. class Derived extends Base
  4. int n
  5. public Derived() n10
  6. public int getValue1() return n
  7. public int getValue2() return super.n
  8. public class TestInheritance
  9. public static void main(String args)
  10. Base b new Base()
  11. Derived d new Derived()
  12. System.out.println("base value "b.n)
  13. System.out.println("derived value "d.n)
  14. System.out.println("derived value
    "d.getValue1())
  15. System.out.println("derived value
    "d.getValue2())

15
Liskovs Substitution Principle
  • If for each object O1 of type S there is an
    object O2 of type T such that for all programs P
    defined in terms of T, the behavior of P is
    unchanged when O1 is substituted for O2 then S is
    a subtype of T.
  • - Barbara Liskov, Data Abstraction and
    Hierarchy, SIGPLAN Notices, 23, 5 (May, 1988)

16
Example LSP
  • class Person
  • public void getName() -----------
  • class Student extends Person
  • public void getName() -----------
  • public double getGPA() ------------
  • Instead of
  • Person p1 new Person()
  • p1.getName()
  • we can use
  • Person p2 new Student()
  • p2.getName()

17
Binding
  • Binding is a two step operation
  • Step 1
  • Static Overloading/Static Binding
  • Step 2
  • Dynamic Binding

18
Binding Static
  • Type (Class) of an object determines which
    method/action you can take on the object.
  • This is a compile time decision.
  • Complex a
  • a.add(b) // O.K.
  • a.add(Hello) // Error
  • Static overloading means that the parameters to a
    method are always deduced statically, at compile
    time.

19
Binding Static
  • class Base
  • private int n
  • public Base(int n) this.n n
  • public void showValue()
  • System.out.println("Base Class")
  • class Derived extends Base
  • private int n
  • public Derived(int n) super(-1) this.n n
  • public void showValue()
  • System.out.println("Derived Class")
  • public class TestInheritance
  • public static void main(String args)
  • Base b new Base(10)
  • Base d new Derived(10)
  • b.showValue()

20
Binding Static
  • In the previous example, you can have both
  • b.showValue()
  • d.showValue()
  • It is because
  • both b and d are of type Base
  • Type Base allows showValue() action
  • Q Why the output is
  • Base Class for b.showValue()
  • and
  • Derived Class for d.showValue()?
  • A

21
Dynamic Binding
  • Check what is the run-time type of the object.
  • The virtual machine walks up the inheritance
    hierarchy until it finds a method of matching
    signature.
  • The first method of the appropriate signature is
    used.

22
Example Dynamic Binding
  1. class Base
  2. public void foo(Base x)
  3. System.out.println("BaseBase")
  4. public void foo(Derived x)
  5. System.out.println("BaseDerived")
  6. class Derived extends Base
  7. public void foo(Base x)
  8. System.out.println("DerivedBase")
  9. public void foo(Derived x)
  10. System.out.println("DerivedDerived")

23
Example Dynamic Binding
  • public class TestInheritance
  • public static void main(String args)
  • Base b new Base()
  • Base d new Derived()
  • b.foo(b)
  • b.foo(d)
  • d.foo(b)
  • d.foo(d)

24
Dynamic Binding
  • All methods and parameters are bound at
  • run time in Java except
  • static methods
  • final methods
  • private methods

25
Downcasting
  • Changing the static type of an expression from a
    base class to a class farther down in the
    inheritance hierarchy.
  • double mygpa
  • Person p1 new Person()
  • Person p2 new Student()
  • mygpa p2.getGPA() // Error
  • mygpa ((Student) p2).getGPA() // O.K.

26
Overriding
  • Overriding implementing a method in a subclass
    that has the same signature as a method in the
    superclass
  • Overriding is based on Dynamic Binding
  • Dont confuse with Overloading methods with
    same name in a class but with different
    signatures

27
Example Overriding
  1. class Base
  2. private int n
  3. public Base(int n) this.n n
  4. public int getValue() return n
  5. class Derived extends Base
  6. private int n
  7. public Derived(int n) super(5) this.n n
  8. public int getValue() return n
  9. public class TestInheritance
  10. public static void main(String args)
  11. Base b new Base(10)
  12. Base d new Derived(10)
  13. System.out.println("base value "
    b.getValue())
  14. System.out.println("derived value
    "d.getValue())

28
Example Partial Overriding
  • Use this programming technique, when you want to
    make a small change in a base class method.
  • Super class Worker has a method doWork(), but sub
    class Workaholic is making a small change
  • public class Workaholic extends Worker
  • public void doWork()
  • super.doWork()
  • drinkCoffee()
  • super.doWork()

29
final
  • final methods can not be overridden.
  • final methods is a more efficient way of
    programming.
  • static binding is used for final methods.
  • final class can not be extended.
  • Any attempt to override a final method is a
    compile time error.
  • All methods in a final class are final methods.

30
Polymorphism
  • Polymorphism the same message can evoke
    different behavior depending on the receiver
  • A reference to the superclass can also reference
    instances of any subclass
  • NOTE The reverse is NOT true

31
Polymorphism
  • Polymorphism the same message can evoke
    different behavior depending on the receiver
  • A reference to the superclass can also reference
    instances of any subclass
  • NOTE The reverse is NOT true

32
The Object class
  • Object is the ultimate super class
  • Every class in Java is directly or indirectly
    derived from the Object class
  • Some methods provided by Object
  • toString()
  • equals()
  • clone()
  • hashcode()

33
  • public class Object
  • public native int hashCode()
  • public boolean equals(Object obj)
  • return (this obj)
  • protected native Object clone() throws
  • CloneNotSupportedExcep
    tion
  • public String toString()
  • return getClass().getName() "_at_"
  • Integer.toHexString(hashCode())

34
Abstract Class
  • Abstract class
  • A class which can not be instantiated
  • A class which must be extended to be
    used
  • An abstract class generally contains one or more
    abstract methods. Such a class must be declared
    as abstract.

35
Example Abstract Class
  1. public abstract class Shape
  2. public abstract double area()
  3. public abstract double perimeter()
  4. public double semiperimeter()
  5. return perimeter()/2

36
Interface
  • Interface
  • Declares features but provide no implementation.
  • Can be used to define a set of constants.
  • Every thing is abstract
  • Used to implement multiple inheritance (No side
    effect of multiple inheritance)
  • A class implements an interface

37
Example Interface
  • interface MyInterface
  • void aMethod(int i) // an abstract method
  • class MyClass implements MyInterface
  • public void aMethod(int i)
  • // implementation details
  • aMethod(int i) is always public static.

38
Example Interface
  • public interface Constants
  • int ONE1
  • public static final int TWO2
  • public static final int THREE3
  • The constants ONE, TWO, THREE can be used
    anywhere in the class implementing Constants.
  • Constants defined inside interface becomes
    automatically public static final.
  • System.out.println(Constants.ONE) // O.K.

39
Example Interface
  • Find an error in the following declaration of
    Constants interface.
  • interface Constants
  • public final int ONE
  • public static final int TWO2
  • public static final int THREE3

40
Why Interface? (1)
  • interface Student
  • float getGPA()
  • interface Employee
  • float getSalary()
  • public class StudentEmploy implements Student,
    Employee
  • public float getGPA()
  • // implementation
  • public float getSalary()
  • // implementation
  • Now,
  • StudentEmploy
  • is
  • both Student and Employee.

41
Why Interface? (2)
  • Consider.
  • Student students new Student10
  • Employee employees new Employee10
  • Since a StudentEmployee can be viewed as both a
    Student and an
  • Employee, we can use the following statements.
  • students0 new StudentEmployee()
  • employees0 new StudentEmployee()

42
Why Interface? (3)Marker Interface
  • Marker Interfaces are empty interfaces, that is,
    interfaces that declare no methods or constants.
  • They are intended to mark classes as having
    certain properties.
  • Cloneable interface is a marker interface.
  • If your class does not implement Cloneable
    interface, you can not define clone method
    properly.

43
Interface Comparable
  • public interface Comparable
  • public int compareTo(Object o)

44
Insertion Sort Integer Array
  • Insertion-Sort (int a)
  • for (int p1 plt inarray.length p)
  • int tmp inarrayp
  • int j
  • for (jp jgt0 inarrayj-1gttmp j--)
  • inarrayj inarrayj-1
  • inarrayjtmp

45
Insertion Sort Comparable Array
  • Insertion-Sort (Comparable a)
  • for( int p1 p lt a.length p )
  • Comparable tmp ap
  • int j
  • for (jp jgt0 tmp.compareTo(aj-1)lt0
    j--)
  • aj aj-1
  • aj tmp

46
Four Kinds of Methods
  • final cannot be overridden (bound at
    compile-time)
  • abstract must be overridden (bound at
    run-time)
  • static no controlling object (bound at
    compile-time)
  • other bound at run-time

47
Merge Sort, p293
  • Merge_Sort(A,p,r)
  • if p lt r
  • q ? (pr)/r
  • Merge_Sort(A,p,q)
  • Merge_Sort(A,q1,r)
  • Merge(A,p,q,r)
  • In here, x means the largest integer less than
    or equal to x.

48
Quick Sort, p295
  • QuickSort(A,p,r)
  • if pltr
  • q ? Partition(A,p,r)
  • QuickSort(A,p,q)
  • QuickSort(A,q1,r)

49
Wrapper Class
  • Incompatible Types
  • Comparable inarray new Comparable10
  • inarray0 10 // compile error
  • inarray1 20 // compile error
  • Correction
  • Integer n1 new Integer(10)
  • inarray0 n1
  • System.out.println(inarray0)

50
List of Wrapper Class
  • All eight primitive types have wrapper classes.
  • Short, Integer, Long
  • Float, Double
  • Boolean
  • Byte, Character
  • Wrapper objects are immutable.

51
Wrapper Class Integer
  • public final class Short
  • extends Number implements Comparable
  • Static Field
  • MAX_VALUE
  • MIN_VALUE
  • SIZE
  • public methods
  • parseInt(String s)
  • toBinaryString(int i)
  • toHexString(int i)
  • intValue()
  • Example
  • System.out.println(Integer.toBinaryString(10)
    )
  • System.out.println(Integer.toHexString(10))

52
Adapters
  • In order to use an interface, you have to
    implement all the methods. Even if you need only
    a single method of them.
  • Example
  • Member Methods of interface WindowListener
  • windowActivated(WindowEvent e)
  • windowClosed(WindowEvent e)
  • windowClosing(WindowEvent e)
  • windowDeactivated(WindowEvent e)
  • windowDeiconified(WindowEvent e)
  • windowIconified(WindowEvent e)
  • windowOpened(WindowEvent e)

53
Adapters
  • Problem. Do you want to implement all the methods
    of WindowListener interface when you need only
    one of them?
  • Adapter class can be used to overcome this
    problem.
  • Look at the example
  • TestWindowListener1.java

54
Anonymous Class
  • Anonymous class is a class with no name.
  • To understand the syntax of anonymous class,
    compare the following examples.
  • Example 1
  • mylabel.addWindowListener(new
    MyWindowAdapter())
  • Example 2
  • mylabel.addWindowListener(new WindowAdapter()
  • public void windowClosing()
  • System.out.println ("System
    Exit")
  • System.exit(0)
  • )
Write a Comment
User Comments (0)
About PowerShow.com