Sie sind auf Seite 1von 31

Chapter 7

inheritance
and
polymorphism
Focus
• To explain inheritance concept,
• To apply inheritance concept in programming.
• To list the types of accessibility modifier
inheritance
to create a new class
(subclass) from the existing
classes (superclass)
What Inheritance is ‘is-a’ relation
Used when in need of a new Rectangle
• Super class – Rectangle
• Sub class – Box
class with a same properties or • Attributes for Rectangle :
method of the current class. double length length, width
double width • Attribute for Box : height

The subclass inherits the Box class inherits the


properties (method and length and width of the
characteristics data / attributes) of the Rectangle class
superclass (superclass)
Box
double height

Circle inherits the Shape class, hence


the Circle is a Shape. (see the next
Example figure)

Every Circle and every Rectangle is


Shape and every Box is a Rectangle
types of inheritances
Is a subclass that derived from a single/one
Single superclass (existing class)

inheritance

Multiple Is a subclass that derived from more than one


superclass (Not supported by Java)
inheritance
Implementing inheritance
• extends is the keyword to implement inheritance in Java.
• Syntax
class SubClassName extends SuperClassName
{
// properties & methods
}
• E.g.
class Box extends Rectangle
{
// properties and coding
}
Example : Rectangle class

The class Rectangle has 9 members


Rectangle
- length : double
- width : double
+ Rectangle()
+ Rectangle(double,double)
+ setDimension(double,double) : void
public class Rectangle {
+ getLength() : double
private double length;
+ getWidth() : double
private double width;
+ area() : double
+ print() : void
public Rectangle(){
UML class diagram of the Rectangle class length = 0;
width = 0;
public double getLength() { }
return length;
} public Rectangle(double L, double W){
setDimension(L,W);
public double getWidth() { }
return width;
} public void setDimension(double L, double W){
if (L >= 0)
public double area() { length = L;
return length * width; else
} length = 0;

public void print() { if (W >= 0)


System.out.print(“length = “ + length); width = W;
System.out.print(“width = “ + width); else
} width = 0;
// end for Rectangle class }
E.g. : Box class
public class Box extends Rectangle{ public double getHeight(){
private double height; return height;
}
public Box(){
super(); public double area(){
height = 0; return 2 * (getLength() * getWidth()
} + getLength() * height
+ getWidth() * height);
public Box(double L, double W, double H){ }
super(L,W);
height = H; public double volume()
} {
return super.area() * height;
public void setDimension(double L, double }
W, double H){
setDimension(L,W); public void print()
if (H >= 0) {
height = H; super.print();
else system.out.print(“height = “ + height);
height = 0; }
}
} // end for class Box extends
UML class diagram
The class Box has 13 members

Box
- height : double
- length : double (can’t access directly)
- width : double (cant’ access directly)
+ Box()
+ Box(double,double)
+ setDimension(double,double) : void
+ setDimension(double,double,double) : void (overloads parent’s setDimension())
+ getLength() : double
+ getWidth() : double
+ getHeight() : double
+ area() : double (overrides parent’s area())
+ volume() : double
+ print() : void (overrides parent’s print())

• The class Box is derived from the class Rectangle


• Therefore, all public members of Rectangle are public members of Box
• The class Box overrides the method print and area
• The class Box has 3 data members : length, width and height
• The instance variable length and width are private members of the class Rectangle
• So, it cannot be directly accessed in class Box
• Use the super keyword to call a method of the superclass.
• To print the length and width, a reserve word super should be put
into the print method of class Box to call the parent’s print() method.

• The same case happen in the volume method where super.area() is


being used to determine the base area of box.

• The method area of the class Box determines the surface area of the
box.

• To retrieve the length and width, the methods getLength and


getWidth in class Rectangle is being used.

• Here, the reserve word super is not used because the class Box does
not override the methods getLength and getWidth
defining classes with
inheritance
• Case Study:
• Suppose we want implement a class roster that contains both
undergraduate and graduate students.
• Each student’s record will contain his or her name, three test
scores, and the final course grade.
• The formula for determining the course grade is different for
graduate students than for undergraduate students.
Undergrads: pass if avg test score >= 70
Grads: pass if avg test score >= 80
Modeling Two Types of Students

•There are two ways to design the classes to


model undergraduate and graduate students.
• We can define two unrelated classes, one for undergraduates and one for
graduates.
• We can model the two kinds of students by using classes that are related in
an inheritance hierarchy.

•Two classes are unrelated if they are not


connected in an inheritance relationship.
Classes for the Class Roster

• For the Class Roster sample, we design three classes:


• Student
• UndergraduateStudent
• GraduateStudent
• The Student class will incorporate behavior and data
common to both UndergraduateStudent and
GraduateStudent objects.
• The UndergraduateStudent class and the GraduateStudent
class will each contain behaviors and data specific to their
respective objects.
Inheritance Hierarchy

+ computeCourseGrade() : int

+ UndergraduateStudent() : void + GraduateStudent() : void


+ computeCourseGrade() : int + computeCourseGrade() : int
Definition of GraduateStudent &
UndergraduateStudent classes

class GraduateStudent extends Student { class UndergraduateStudent extends Student {

//constructor not shown //Constructor not shown

public void computeCourseGrade() {


public void computeCourseGrade() { int total = 0;
int total = 0;
total = test1 + test2 + test3;
total = test1 + test2 + test3;
if (total / 3 >= 70) {
if (total / 3 >= 80) { courseGrade = "Pass";
courseGrade = "Pass"; } else {
} else { courseGrade = "No Pass";
courseGrade = "No Pass"; }
} }
}
} }
Declaring a Subclass

A subclass inherits data and methods from the superclass. In


the subclass, you can also:
 Add new data
 Add new methods
 Override the methods of the superclass
 Modify existing behaviour of parent
Overriding vs. Overloading

public class Test { public class Test {


public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
} }
} }

class B { class B {
public void p(int i) { public void p(int i) {
} }
} }

class A extends B { class A extends B {


// This method overrides the method in B // This method overloads the method in B
public void p(int i) { public void p(double i) {
System.out.println(i); System.out.println(i);
} }
} }
Inheritance Rules

1. The private members of the superclass are private to the superclass


2. The subclass can access the members of the superclass according to the
accessibility rules
3. The subclass can include additional data and/or method members
Inheritance Rules (continued)
4. The subclass can override, that is, redefine the methods of the
superclass
 The overriding method in subclass must have similar
 Name
 Parameter list
 Return type

5. All members of the superclass are also members of the subclass


• Similarly, the methods of the superclass (unless overridden) are also the
methods of the subclass
• Remember Rule 1 & 2 when accessing a member of the superclass in the
subclass
Inheritance Rules (continued)

6. (Using the Keyword super)

The keyword super refers to the direct


superclass of a subclass . This keyword can
be used in two ways:
• To call a superclass constructor
• super(); //must be the first statement in subclass’s constructor
• To call a superclass method
• super.methodname();
• this is only used if the subclass overrides the superclass method
The Object Class is the Superclass of Every Java Class
INHERITANCE

(Accessibility Modifier)

• Sometimes , it is called visibility modifier


• Not all properties can be accessed by sub class.
• Super class can control a data accessing from subclass by giving the
type of accessing to the members and methods.
• A class can declare the data members or method as a public, private
or protected.
• If it is not declared, the data or method will be set to default type.
INHERITANCE

Member Accessibility

Accessibility criteria
Modifier Same Class Same Subclass Universe
Package
private Yes No No No

default Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes


INHERITANCE
Data Accessibility
Super class
Package A
int a
public int b
Package B protected int c
private int d

Sub class B Sub class A

int a
public int b
public int b
protected int c
protected int c
Refer to the previous slide

• Super class has 2 subclasses : Subclass A and


Subclass B.

• Subclass A is defined in same package with


superclass, subclass B is defined outside the package.

• There are 4 accessibility data types: public, protected,


private and default.

• Subclass A can access all properties of superclass


except private.

• But, subclass B can only access the properties outside


the package which are public and protected.
Example: Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }
class ClassX
What’s {
wrong with private int m;
the code? public String toString()
How to fix {
it? return new String("(" + m + ")");
}
}
public class ClassY extends ClassX
{
private int n;
public String toString()
{
return new String("(" + m + " , " + n + ")");
}
}

class TestAccesibility
{
public static void main(String [] args)
{
ClassX x = new ClassX;
ClassY y = new ClassY;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
Inheritance and Constructors
• Unlike members of a superclass, constructors of a superclass are not
inherited by its subclasses.
• You must define a constructor for a class or use the default constructor
added by the compiler.
• The statement
super();
calls the superclass’s constructor.
• super(); must be the first statement in the subclass contructor.
• A call to the constructor of the superclass
must be in the first statement in the child
constructor.

public Box(double l, double w, double h)


{
super(l,w);
height = h;
}
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);
Superclass’s Constructor Is Always Invoked

A subclass constructor may invoke its superclass’s


constructor. If none is invoked explicitly, the compiler
puts super() as the first statement in the constructor.
For example, the constructor of class A:

public A() { public A() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}
Example on the Impact of a Superclass without no-arg Constructor

Find out the error in the program:

class Fruit {
public Fruit(String name) {
System.out.println("Fruit constructor is invoked");
}
}

public class Apple extends Fruit {


public Apple(String name) {
System.out.println(“Apple constructor is invoked");
}
}

Das könnte Ihnen auch gefallen