8 Inheritance
8 Inheritance
8 Inheritance
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
inheritance
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 method area of the class Box determines the surface area of the
box.
• 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
+ computeCourseGrade() : int
class B { class B {
public void p(int i) { public void p(int i) {
} }
} }
(Accessibility Modifier)
Member Accessibility
Accessibility criteria
Modifier Same Class Same Subclass Universe
Package
private Yes No No No
int a
public int b
public int b
protected int c
protected int c
Refer to the previous slide
package p2;
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.
class Fruit {
public Fruit(String name) {
System.out.println("Fruit constructor is invoked");
}
}