Chapter 4 Inheritance Class
Chapter 4 Inheritance Class
Chapter 4 Inheritance Class
2
Objectives
To encapsulate data fields to make classes easy to
maintain
To discuss the basic concept of inheritance
To introduce the notions of abstract methods,
abstract
classes, and interfaces.
To introduce issues that arise with subclasses
protected
- visibility, use of the super() constructor
To discuss the notion of multiple inheritance
and Java’s approach to it
3
Content
Inheritance
Method overloading and overriding
Abstract classes and Interfaces
4
Fundamental OOP Concepts
Encapsulation is one of the fundamental OOP concepts.
The other two are inheritance and polymorphism.
Encapsulation is combining data and behavior in one
package and hiding the implementation details. It is the
technique of making the fields in a class private and
providing access to the fields via public methods.
Encapsulation is also referred to as data hiding.
Benefit: the ability to modify our implemented code
without breaking the code of others who use our code.
5
OOP Concepts(cont’d)
In OO systems, the class is the basic unit of encapsulation.
For example, you can create a Circle object and find the area
of the circle without knowing how the area is computed.
Benefits of Encapsulation
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data.
The fields of a class can be made read-only or write-only.
6
Encapsulation(Example)
public class EncapTest{
private String name;
private String
idNum; private int
age;
public int getAge(){
return age;
}
publicString getName(){
return name;
}
publicString getIdNum(){
return idNum;
}
7
Example(cont’d)
publicvoid setAge(int newAge){
age = newAge;
}
publicvoid setName(String newName){
name = newName;
}
public void setIdNum(String newId){
idNum = newId;
}
}
8
Example(cont’d)
public class RunEncap{
public static void main(String args[]){
EncapTest encap =new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : "+ encap.getName()+"
Age : "+ encap.getAge());
}
}
Output
Name: James Age:20
9
Inheritance
Inheritance can be defined as the process where one object
acquires the properties of another.
It allows you to derive new classes from existing classes.
Allows reusing software.
E.g.
Suppose you want to design the classes to model geometric objects
such as circles and rectangles.
Geometric objects have many common properties and behaviors: can
be drawn in a certain color, filled or unfilled. Thus a general class
GeometricObject can be used to model all geometric objects.
10
Inheritance(cont’d)
11
Inheritance(cont’d)
One of the main uses of inheritance is to model
hierarchical
structures that exist in the world.
Example: Consider people at AASTU. Broadly speaking, they fall
into two categories: employees and students.
There are some features that both employees and students have in
common - whether a person is an employee or a student, he or she
has a name, address, date of birth, etc.
There are also some features that are unique to each kind of person
e.g. an employee has a pay rate, but a student does not; a
student has a GPA, but an employee does not, etc.
12
Inheritance(cont’d)
13
Inheritance(cont’d)
With this structure, the classes Employee and Student inherit all
the features of the class Person.
In addition, each of the classes Employee and Student can have
features of its own not shared with the other classes.
To inherit a class, you simply incorporate the definition of one
class into another by using the extends keyword.
For example, we could declare classes Person, Employee, and
Student as follows:
class Person {
...
}
class Employee extends Person {
...
}
class Student extends Person {
...
} 14
Inheritance(cont’d)
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
Now, based on the above example, in Object Oriented terms the
following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes
A subclass and its superclass must have the is-a relationship
Now, if we consider the IS-A relationship, we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well 15
Inheritance(cont’d)
Basic terminology: If a class B inherits from a class A:
We say that B extends A or B is a subclass of A - So we say
Employee extends Person, or Employee is a subclass of Person.
We say that A is the base class of B or the superclass of B - So we
say Person is the base class of Employee, or the superclass of
Employee.
A key aspect of inheritance is that a subclass inherits all the
features of its base class except for the private properties of
the superclass.
A subclass is not a subset of its super-class. In fact, a subclass
usually contains more information and methods than its
superclass.
16
Inheritance(cont’d)
Consider the following example of a class hierarchy for
bank accounts.
17
Inheritance(cont’d)
Savings account adds features that an ordinary BankAccount
does not have - e.g. payInterest() and setInterestRate().
CheckingAccount overrides the withdraw() method of
BankAccount.
a) In the special case where the checking account balance is
insufficient for the withdrawal, but the customer has a savings
account with enough money in it, the withdrawal is made from
savings instead.
b) In all other cases, the inherited behavior is used by invoking
super.withdraw(amount).
18
Inheritance(cont’d)
In designing a class hierarchy, methods should be placed at
the appropriate level. For example, in the BankAccount
Example:
deposit(), reportBalance(), and getAccountNumber() are defined in
the base class BankAccount, and so are inherited by the two
subclasses.
If they were defined in the subclasses, we would have to repeat
the code twice - extra work and an invitation to inconsistency.
On the other hand, payInterest() and setInterestRate() are defined
in SavingsAccount, because they are not relevant for
CheckingAccounts.
withdraw() is defined in BankAccount and overridden in
CheckingAccount. Why is this better than simply defining separate
versions in CheckingAccount and SavingsAcccount?
19
Types of Inheritance
On the basis of class, there can be three types of inheritance in
java: single, multilevel and hierarchical.
In java programming, multiple and hybrid
inheritance is supported through interface only.
20
Types of Inheritance(cont’d)
21
Types of Inheritance(cont’d)
22
Example: Single
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void
showij()
{
System.
out.printl
n("i and
j: " + i +
" " + j);
}
}
// Create a subclass by extending class
A. class B extends A {
int k;
void showk() 23
Example(cont’d)
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new
A(); B subOb = new
B();
// The superclass
may be used by
itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb:
"); superOb.showij();
System.out.println();
24
Example(cont’d)
/* The subclass has access to all public members
of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb:
"); subOb.showij();
subOb.showk();
System.out.println();
System.out.println("
Sum of i, j and k in
subOb:");
subOb.sum();
}
}
25
Example(cont’d)
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
26
Exercise
If you have identified the following three classes: Taxi,
Truck, & Automobile, how do you design the classes
using inheritance concept?
27
Method overloading
Methods of the same name can be declared in the same class,
as long as they have different sets of parameters. This is called
method overloading.
Method overloading is commonly used to create several
methods with the same name that perform the same or similar
tasks, but on different types or different numbers of arguments.
Method calls cannot be distinguished by return type if they have
the same number and type of parameters.
E.g. If we define method: public int square(int no);
It is not allowed to define another method like this:
public double square(int no);
28
Example
public class MethodOverload{
// test overloaded square methods
public void testOverloadedMethods(){
System.out.printf( "Square of integer 7 is " +square( 7 ) );
System.out.printf( "Square of double 7.5 is" + square( 7.5 ) );
}
public int square( int intValue ){
System.out.printf( "Called square with int argument:" +intValue );
return intValue * intValue;
}
public double square( double doubleValue )
{ System.out.printf( "\nCalled square with double
argument:"
+doubleValue );
return doubleValue * doubleValue;
}
}
29
Example(cont’d)
public class
MethodOverloadTest{ public static
void main( String args[] ){
MethodOverload methodOverload = new MethodOverload();
methodOverload.testOverloadedMethods();
}
}
30
Method overriding
Overriding means to provide a new implementation for
a
method in the subclass.
To override a method, the method must be defined in the
subclass using the same signature and the same return type
Benefit of overriding is ability to define a behavior that's
specific to the subclass type which means a subclass can
implement a parent class method based on its requirement.
31
Example1
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
32
Example1(cont’d)
public class TestDog{
public static void main(String args[]){
Animal a =new Animal();// Animal reference and object
Animal b =new Dog();// Animal reference but Dog
object a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
Program Output
Animals can move
Dogs can walk and run
33
Example 2
class Animal2{
public void move(){
System.out.println("Animals can move");
}
}
class Dog2 extends
Animal2{ public void
move(){
System.out.println("Dogs
can walk and run");
}
37
The super keyword(cont’d)
If a class is designed to be extended, it is better to provide a no-arg
constructor to avoid programming errors.
Example:
class Fruit{
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
public class Apple extends Fruit {
}
Since Apple is a subclass of Fruit, Apple’s default constructor automatically
invokes Fruit’s no-arg constructor. However, Fruit does not have a no-arg
constructor, because Fruit has an explicit constructor defined. Therefore,
the program cannot be compiled.
38
The super keyword(cont’d)
(II) To call a superclass method, when invoking a superclass version
of an overridden method.
Syntax: super.method(parameters);
39
The super keyword(cont’d)
Example
class Animal3{
public void move(){
System.out.println("Animals can move");
}
}
class Dog3 extends Animal3{
public void move(){
super.move();// invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog3{
public static void main(String args[]){
Animal3 b =new Dog3();// Animal reference but Dog object
b.move();//Runs the method in Dog class
}
}
program Output
Animals can move
40
Dogs can walk and run
Exercise 1
What will be an output of the following program?
public class Test{
public static void main(String[] args) {
A a = new A(3);
}
}
class A extends B {
public A(int t) {
System.out.println("A's constructor is
invoked");
}
}
class B {
public B() {
System.out.println("B's constructor is
invoked");
}
}
Output: B's constructor is invoked
A's constructor is invoked 41
Exercise 2
1. Identify error in the following program
class A {
public A(int x) {
System.out.println(“A’s Constructor”);
}
}
class B extends A {
public B() {
System.out.println(“B’s Constructor”);
}
}
public class C {
public static void main(String[] args) {
B b = new B();
}
}
Error:
Can’t find constructor A()
42
Exercise 3
class Room{ class Test{
int l,w; public static void main(String [] args){
Room(int x, int y){ BedRoom room1=new BedRoom(14,12,10);
l=x; System.out.println("Area1="+room1.area());
w=y;
} System.out.println("Volume1="+room1.volum
int area(){ e());
return (l*w); } }
}
}
class BedRoom extends Room{ Output
int h;
Areaa1=168
BedRoom(int x, int y, int z){
super(x,y); Volume1=1680
h=z;
}
int volume()
{ return(l*h*
w);
}
}
43
Abstract Class
When we define a superclass, we often do not need
to create any instances of the superclass. An abstract
class is one that cannot be instantiated.
An abstract class must include the keyword abstract
in its definition.
An abstract class has an incomplete definition
because the class includes the abstract method that
does not have a method body.
E.g abstract class AbstractClass{
}
44
An abstract method
An abstract method is a method with the keyword
abstract, and it ends with a semicolon instead of a
method body. E.g abstract abMethod();
If you want a class to contain a particular method but you
want the actual implementation of that method to be
determined by child classes, you can declare the method
in the parent class as abstract.
An abstract method consists of a method signature, but no
method body.
A class is abstract if the class contains an abstract
method or does not provide an implementation of an
inherited abstract method.
45
Example
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract
classes void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
46
Example(cont’d)
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Output
B’s
implementation of
callme
This is concrete
method
47
Which of the following class definition is valid?
public class abstract
Ck{ String s;
abstract void name(){
this.s
=s;
return s;
}
48
Interfaces
Using interface, you can specify what a class must do,
but not how it does it.
Once an interface has been defined, one or more
classes can implement that interface.
An interface is not a class. A class describes the
attributes and behaviors of an object. An interface
contains behaviors that a class implements.
An interface is similar to a class in the following ways:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
The bytecode of an interface appears in a .class file.
49
Interfaces(cont’d)
interface is different from a class in several ways:
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields
that can appear in an interface must be declared as static.
An interface is not extended by a class; it is implemented by
a class.
50
Defining an Interface
general form of an interface:
access interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations
}
access is either public or not used(default)
Variables can be declared inside of interface declarations. They
are implicitly final and static, meaning they cannot be changed
by the implementing class.
example of an interface definition:
interface Callback {
void callback(int param);
}
51
Implementing Interfaces
To implement an interface, include the implements
clause in a class definition, and then create the
methods defined by the interface.
The general form:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}
52
Example
interface AnimalInterface{
public void eat();//abstract methods
public void travel();//abstract methods
}
54
Inheritance versus Interface
They are similar because they are both used to model
an IS-A relationship.
We use the Java interface to share common behavior
(defined by its abstract methods) among the instances
of unrelated classes.
We use inheritance, on the other hand, to share
common code (including both data members and
methods) among the instances of related classes.
Use the Java interface to share common behavior.
Use the inheritance to share common code
55
Abstract class Vs. Interface
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods,
method and constructor. main method or constructor.
56
Multiple Inheritance
Multiple inheritance - a class can inherit properties of more
than
one parent class.
Why java doesn’t support multiple inheritance?
To avoid ambiguity
57
Example
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
58
Example: Multiple inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
59
Questions
How we prevent classes from being extended?
Why java doesn’t “support” multiple inheritance? If
multiple inheritance is required how do we
implement?
What is dynamic binding?
60