0% found this document useful (0 votes)
54 views

05 Inheritance

This document discusses inheritance in object-oriented programming. It defines inheritance as a class hierarchy where a subclass inherits fields and methods from its parent superclass. Subclasses can override methods and fields from the superclass. The document provides examples of defining superclasses and subclasses, using the super keyword to call parent constructors and methods, and overriding methods and fields in subclasses.

Uploaded by

Nur Madihah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

05 Inheritance

This document discusses inheritance in object-oriented programming. It defines inheritance as a class hierarchy where a subclass inherits fields and methods from its parent superclass. Subclasses can override methods and fields from the superclass. The document provides examples of defining superclasses and subclasses, using the super keyword to call parent constructors and methods, and overriding methods and fields in subclasses.

Uploaded by

Nur Madihah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 26

CHAPTER 5 :

INHERITANCE

CSC 238 (Object Oriented Programming I)


Inheritance concept
 Class hierarchy
 Capability of deriving one class from another
class
 OOP allows classes to inherit commonly used
fields and methods from other classes.
 It is simple and powerful – when you want to
create a new class and there is already a class
that has some of the codes that you want, then
you can derive a new class from the existing
one – save time of writing those codes
yourself.
Inheritance concept
 The existing class is called the parent,
superclass or base class.
 the derived class is called child class or
subclass.
 The child inherits characteristics of the parent.
– inherits all the members (fields, methods and
nested classes)
 Constructors are not members, so they are not
inherited by subclasses but the constructors of
the superclass can be invoked from the
subclass.
Inheritance concept
Super class
Circle
• is general purpose class

Cone Cylinder Sub-Class


• special case or
•customized version
•of the super class
 Format for superclass :-
example :
public class Circle
{ // data and methods for the superclass }

 Format for subclass :-


example – Cylinder class
public class Cylinder extends Circle
{ // new characteristics of a child class….}
Inheritance concept
 Inheritance relationships – shown graphically in a
class diagram, with the arrow pointing to the parent
class
 Inheritance should create an is-a relationship, where a
child is a more specific version of its parent.

Circle Cylinder
Circle
-Radius : double -height : double

+ Circle(double r) + Cylinder(double r,
Cylinder + calcArea() : double double l)

The figure shows the relation between Circle and Cylinder classes in an inheritance relationship
Inheritance concept
 Inheritance is one-way proposition; a child
inherits from a parent but not the other way
around.
 Super class does not have access to the
subclass methods.
 When creating a parent class, programmer
does not know how many subclasses are
there and what are their data or methods to
be.
Access Level – Data & Methods
 Public
 Data and methods can be accessed anywhere class name is
accessible

 Private
 Data and methods can be accessed within a class.

 Protected
 behaves similar to private modifier, can only be accessed within a
class but can be extended to be accessed in all subclasses.

 If no access level is specified


 Accessible in the package that contains the class
 Accessible in subclasses defined in the package that contains the
class
Constructor
 A special type of instance method that creates a new
object.
 In Java, it has the same name as its class and no return
value
 Purpose is to create an instance of a class – initializing
the property : giving an object properties an initial value
 If a class does not have constructor, Java will
automatically supply a default constructor.
 Different from other Java methods :
 Never has an explicit return type.
 Cannot be directly invoked must used keyword “new”
 Cannot be overridden or inherited
 Cannot be final, abstract or static
Constructor
 Constructors of a superclass are not inherited
by its subclasses, even though they have
public visibility.
 You must define a constructor for a class or
use the default constructor added by the
compiler.
 a constructor in a child class always starts with
an invocation of one of the constructors in the
parent class, if there are many then use the
one which is invoked.
The super Reference
 To refer to members of the parent class.
 The statement :
super();
calls the superclass constructor
 The statement :
super.calcArea()
calls the superclass method name calcArea()in the
superclass.
Example 1 :
public class Circle public class Cylinder extends Circle
{ {
//class variable declaration section //class variable declaration section
public final static double PI = 3.142; // additional data member
protected double radius; protected double length;

// constructor // constructor
public Circle(double r) public Cylinder(double r, double l)
{ radius = r; { super(r);
} length = l;
}
// calculate the area of a circle
public double calcArea() // calculate a volume of cylinder
{ return (PI * radius * radius); public double calcval()
} { return (super.calcArea() * length);
}
public class CalculateCircle
{
public static void main (String[] args)
{
Circle c1 = new Circle(2.50);
Circle c2 = new circle(5.50);
Cylinder c3 = new Cyclinder(3, 4);

System.out.println(“The area of circle 1 “ + c1.calcArea());


System.out.println(“The area of circle 2 “ + c2.calcArea());
System.out.println(“The volume of a cylinder is “ + c3.calcval());
}
}
Example 2:
public class Customer public class RegularCustomer extends
{ Customer
{
private int idNum;
double discount;
private double balance;
public Customer(int id, double bal)
public RegularCustomer(int id, double
{
bal, double disc)
idNum = id;
{ super(id, bal);
balance = bal;
discount = disc;
}
}
public void display()
{
public void display()
System.out.printly(“Customer
Num “ + idNum + “Balance RM {
“ + balnce); super.display();
} System.out.println(“Discount is “ +
} discount);
}
}
public class CustomerTest
{
public static void main (String[] args)
{
Customer C = new Customer(123, 25.00);
RegularCustomer R = new RegularCustomer(111, 37.50, 0.25);

C.display();
R.display();
}
}
Overriding Fields and Methods
Overriding Methods
 Different methods have the same name
 The methods have the same name and parameter
type list and declared in different classes.
 They must have the same return types.
 A public method can be overridden only by another
public method.

Overriding fields
 is similar to overriding methods – they have the same
declarations but in different classes.
Overriding Fields and Methods
public class ClassX public class ClassY extends ClassX
{ {
protected int m; private double n; //overrides field ClassX.n
protected int n;
public void g() //overrides method ClassX.g()
public void f() {
{ System.out.println(“Now in ClassY.g().”);
System.out.println(“Now in ClassX.f() “); n = 3.141678;
m = 22; }
}
public void g() public String toString()
{ //overrides method ClassX.toString()
System.out.println(“Now in ClassX.g(). {
“); return new String(“{ m= “ + m + “, n= “ + n + “}”);
n = 44; }
} }
Public String toString()
{
return new String(“{ m= “ + m + “, n= “ +
n + “}”);
}
}
Overriding Fields and Methods
public class TestClassY
{ OUTPUT :
public static void main (String[] args)
{
ClassX x = new ClassX(); Now in ClassX.f()
x.f(); Now in ClassX.g()
x.g(); x = { m=22, n=44}
System.out.println(“x = “ + x); Now in ClassX.f()
Now in ClassY.g()
ClassY y = new ClassY(); y = {m=22, n=3.141678}
y.f();
y.g();
System.out.println(“y = “ + y);

}
}
Methods Cannot be Overridden

 Three types of methods that cannot be


overridden in a subclass :-
1. static methods
2. final methods
3. Methods within final classes
Class Hierarchies
 A class can have more than one subclass and
a subclass can have subclasses :
 Class Y is a descendant of class X if there is a
sequence of classes beginning with Y and
ending with X within which each class is the
superclass of the one before it.
 Within a class hierarchies, 2 types of classes
 Abstract classes – uses abstract modifier
 Final classes – uses final modifier
Abstract Classes
 Is a class that is not concrete – cannot be instantiated
– cannot use the new operator
 Have at least one or more empty abstract methods.
 Use the keyword abstract when you declare the class.
 Objective : is to provide a superclass from which
objects can inherit.
 Abstract method = a method that has no body, no
curly braces and no method statements.
 Abstract method only has a keyword abstract and the
header including method type, name and arguments.
eg. public abstract void speak();
 The subclass method must override the empty
superclass method that is inherited.
Example Abstract Class
public abstract class Animal public class Dog extends Animal
{ {
private String nameOfAnimal; public void speak()
public abstract void speak();
{
public String getAnimalName()
{ return nameOfAnimal; } System.out.println(“Woof!!”);
}
public void setAnimalName(String name) }
{ nameOfAnimal = name; }
}
public class Cow extends Animal
{
public void speak()
{
System.out.println(“Moo!!”);
}
}
Public class UseAnimals
{
public static void main (String args[])
{
Dog mydog = new Dog();
Cow mycow = new Cow();
mydog.setAnimalName(“My dog Murphy”);
mycow.setAnimalName(“My cow Elsie”);
System.out.println(mydog.getAnimalName() + “ says “ );
mydog.speak();
System.out.println(mycog.getAnimalName() + “ says “ );
mycow.speak();
}
}
Dynamic Method Binding
 Each object of each subclass “is a” superclass object. But not the
opposite way.
 You can indirectly create a reference to a superclass abstract
object.
 A reference is not an object but it points to a memory address –
create variable name that hold the memory address of a
concrete object.
 A reference can be created to refer to an abstract superclass
object but store a concrete subclass object there.
 Whenever you code
CLASSNAME OBJECTNAME;
you are created a reference to object, then you code
OBJECTNAME = new CLASSNAME;
you actually set aside memory for the OBJECTNAME
Example :
public class AnimalReference
{
****The variable ref is a type
public static void main (String args[])
of Animal, but no superclass
{ Animal object is created,
Animal ref; instead Dog and Cow objects
ref = new Cow(); are created using the keyword
ref.speak(); new.
ref = new Dog();
ref.speak()
}
}
Arrays of Subclass Objects
 You want to create a superclass reference and treat
subclass objects as superclass objects so you can
create an array of different objects that share the
same superclass.
 The objects in the array has access to the same
method of the superclass.
 When you create an array of any type of objects,
concrete or abstract – you are creating a space for
reference to objects that are not yet instantiated.
 After the objects are in the array, it can be
manipulated like any array objects – such as for loop
Example :
Public class AnimalArray
{
public static void main(String args[])
***Each array referred to a new instance
{ of each object, and can be manipulated
Animal[] ref = new Animal[2]; using for loop and a subscript to get
ref[0] = new Dog(); each individual reference to speak().
ref[1] = new Cow();

for (int x = 0; x < 2; x++)


ref[x].speak;
}
}

You might also like