0% found this document useful (0 votes)
8 views41 pages

Java Inheritance Explained

Chapter 4 discusses inheritance in Object-Oriented Programming (OOP) using Java, explaining how subclasses can inherit properties and methods from parent classes. It covers various types of inheritance, such as single, multilevel, and hierarchical, along with access modifiers and method overriding. The chapter emphasizes the benefits of inheritance, including code reusability and increased reliability in software development.

Uploaded by

habtshehabtshe23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views41 pages

Java Inheritance Explained

Chapter 4 discusses inheritance in Object-Oriented Programming (OOP) using Java, explaining how subclasses can inherit properties and methods from parent classes. It covers various types of inheritance, such as single, multilevel, and hierarchical, along with access modifiers and method overriding. The chapter emphasizes the benefits of inheritance, including code reusability and increased reliability in software development.

Uploaded by

habtshehabtshe23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

CHAPTER 4:

Inheritance

By: Tariku

1
OOP Introduction
Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It
simplifies software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Encapsulation
Polymorphism
Abstraction
2
Inheritance
•Inheritance in Java is a mechanism in which one object acquires all
or some of the properties and behaviors of a parent classes object.
•It is an important part of OOPs (Object Oriented programming system).
•The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes.
•When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and
fields in your current class also.

3
Terms used in Inheritance
•Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects
are created.
•Sub Class/Child Class: Subclass is a class which inherits
the other class. It is also called a derived class, extended
class, or child class.
•Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a base
class or a parent class.
•Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a
new class. You can use the same fields and methods already
4
defined in the previous class.
Cont’d
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new


class that derives from an existing class.
The meaning of "extends" is to increase the functionality.

5
Examples

class Employee{
float salary=4000;
}
class Programmer extends Employee{
int bonus=100;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
6
Types of inheritance in
java
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. We will learn about interfaces later.

7
Cont’d
When one class inherits multiple classes, it is known as multiple
inheritance. For Example:

8
Single Inheritance
Example
When a class inherits another class, it is known as a single inheritance.
In the example given below, Dog class inherits the Animal class, so
there is the single inheritance.
class Animal{
void eat() {[Link]("eating...");}
}
class Dog extends Animal{
void bark() {[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}} 9
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel
Example
inheritance. As you can see in the example given below, Baby Dog
class inherits the Dog class which again inherits the Animal class, so
there is a multilevel inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link](); 10
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known
as hierarchical inheritance. In the example given below, Dog and Cat
classes inherits the Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}} 11
Access Modifiers
Java provides a number of access modifiers to set access
levels for classes, variables, methods, and constructors.
The four access levels are −
•Visible to the package, the default. No modifiers are
needed.
•Visible to the class only (private).
•Visible to the world (public).
•Visible to the package and all subclasses (protected).

The access modifiers in Java specifies the accessibility


or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it. 12
There are four types of Java access modifiers:
public:
 When a member of a class is specified by the public specifier, then that member can be
accessed by any other code.
 The public modifier makes a method or variable completely available to all classes.
 Also when the class is defined as public, it can be accessed by any other class.
private:
 To hide a method or variable from other classes, private modifier is used.
 A private variable can be used by methods in its own class but not by objects of any
other class.
 Neither private variables nor private methods are inherited by subclass.
 The only place these variables and methods can be seen is from within their own
class. 13
Cont’d
protected:
 protected applies only when inheritance is involved.
 If you want to allow an element to be seen outside your current package, but only to
classes that are inherited from your class directly, then declare that element as
protected.
default:
 Classes written like this are not accessible in other package.
 Any variable declared without a modifier can be read or changed by any other class in
the same package.
 Any method declared the same way can be called by any other class in the same
package.
 When a member does not have an explicit access specification,
 it is visible to subclasses as well as to other classes in the same package.
14
The following table summarizes the levels of access control.

Access Public Protected Default Private

From the same class Yes Yes Yes Yes

From any class in the same package Yes Yes Yes No

From any class outside the package Yes No No No

From a sub - class in the same


Yes Yes Yes No
package
From a sub - class outside the same
Yes Yes Yes No
Package 15
Overriding methods
Inheritance
Methods allows a software developer to reuse a sequence of
statements
Inheritance allows a software developer to reuse classes by
deriving a new class from an existing one
The existing class is called the parent class, or superclass, or
base class
The derived class is called the child class or subclass.
As the name implies, the child inherits characteristics of
the parent
That is, the child class inherits the methods and data
defined for the parent class

10
Deriving Subclasses
In Java, we use the reserved word extends to
establish an inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}

class Bird extends Animal


{
// class contents
public void fly() {…};
}

10
Class Hierarchy
A child class of one parent can be the parent
of another child, forming class hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 At the top of the hierarchy there’s a default class called


Object. 11
Class Hierarchy
Good class design puts all common features as high in the
hierarchy as reasonable
inheritance is transitive
An instance of class Parrot is also an instance of Bird, an
instance of
Animal, …, and an instance of class Object
The class hierarchy determines how methods are executed:
Previously, we took the simplified view that when variable v is
an instance of class C, then a procedure call v.proc1() invokes
the method proc1() defined in class C
However, if C is a child of some superclass C’ (and hence v is
both an instance of C and an instance of C’), the picture
becomes more complex, because methods of class C can
override the methods of class C’ (next two slides).
1
Defining Methods in the Child Class:
Overriding by Replacement
 A child class can override the definition of an inherited
method in favor of its own
 that is, a child can redefine a method that it inherits from
its parent
 the new method must have the same signature as the
parent's method, but can have different code in the body

 In java, all methods except of constructors override the


methods of
their ancestor class by replacement. E.g.:
 the Animal class has method eat()
 the Bird class has method eat() and Bird extends Animal
 variable b is of class Bird, i.e. Bird b = …
 [Link]() simply invokes the eat() method of the Bird class

 If a method is declared with the final modifier, it


cannot be
overridden
1
Base
class
1) a class obtains variables and methods from
another class is called subclass, the latter super-class
2)the former
(Base class)
3)a sub-class provides a specialized behavior with
respect to its super-class
4)inheritance facilitates code reuse and avoids
duplication of data
Extends
 Is a keyword
Allows used rom
to extend to inherit a class
only one from another class
class
 f class Two extends One
class One
{
{ int
a=5; int b=10;

} }
Subclass, Subtype and Substitutability
A subtype is a class that satisfies the principle
of
substitutability.
A subclass is something constructed using inheritance,
whether or not it satisfies the principle of substitutability.
The two concepts are independent. Not all subclasses are
subtypes, and (at least in some languages) you can
construct subtypes that are not subclasses.
Substitutability is fundamental to many of the
powerful software development techniques in OOP.
The idea is that, declared a variable in one type may
hold the value of different type.
Substitutability can occur through use of inheritance,
whether using extends, or using implements keywords.
Subclass, Subtype, and Substitutability
When new classes are constructed using inheritance, the argument
used to justify the validity of substitutability is as follows;
• Instances of the subclass must possess all data fields
associated
with its parent class.
• Instances of the subclass must implement, through inheritance
at least, all functionality defined for parent class. (Defining new
methods is not important for the argument.)
• Thus, an instance of a child class can mimic the behavior of the
parent class and should be indistinguishable from an instance of
parent class if substituted in a similar situation.
Subclass, Subtype, and Substitutability
The term subtype is used to describe the relationship between types that explicitly

recognizes the principle of substitution.


A type B is considered to be a subtype of A if an instances of B can legally be

assigned to a variable declared as of type A.

The term subclass refers to inheritance mechanism made by extends keyword.

 Not all subclasses are subtypes. Subtypes can also be formed

using interface, linking types that have no inheritance relationship.


The Benefits of Inheritance
Software Reusability (among projects)

Increased Reliability (resulting from reuse and sharing of well-

tested code)
Code Sharing (within a project)

Consistency of Interface (among related objects)

Software Components

Rapid Prototyping (quickly assemble from pre-existing

components)
Polymorphism and Frameworks (high-level reusable
Using final with inheritance
final keyword is used declare constants which can not
change its value of definition.

final Variables can not change its value.

final Methods can not be Overridden or Over Loaded

final Classes can not be extended or inherited


Preventing Overriding with final
A method declared final cannot be overridden in
any sub-class:
class A {
final void meth() {
[Link]("This is a final method.");
}
}
This class declaration is illegal:
class B extends A {
void meth()
{ [Link]("Illegal!");
}
}
Preventing

Inheritance with final
A class declared final cannot be inherited –
has no sub- classes.
final class A { … }

This class declaration is considered illegal:


class B extends A { … }

Declaring a class final implicitly declares all


its methods
final.

It is illegal to declare a class as both abstract


and final.
Method Overriding

When a method of a sub-class has the


same name and type as a method of the
super-class, we say that this method is
overridden.

When an overridden method is called from


within the sub-class:
1)it will always refer to the sub-class
method

2)super-class method is hidden


Examples:
class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal {
public void move() {
[Link]("Dogs can walk and run");
}
}
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
[Link](); // runs the method in Animal class
[Link](); // runs the method in Dog class
}
}
Example2
class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal {
public void move() {
[Link](); // invokes the super class method
[Link]("Dogs can walk and run");
}
}
public class Labb1 {

public static void main(String args[]) {


Animal b = new Dog(); // Animal reference but Dog object
[Link](); // runs the method in Dog class
}
} //When invoking a superclass version of an overridden method
the super keyword is used.
Overloading vs. Overriding
Overloading deals with Overriding deals with two
multiple methods in the methods, one in a parent class
same class with the same and one in a child class, that
name but different have the same
signatures/parameters signature/parameter
Overloading lets you define a
similar operation in different o Overriding lets you define a
ways for different data similar operation in different
ways for different object types
Abstract Classes
Java allows abstract classes
use the modifier abstract on a class header to declare
an
abstract class
abstract class Vehicle
{ … }
An abstract class is a placeholder in a class hierarchy
that represents aVehicle
generic concept

Car Boat Plane


Abstract Class: Example
 An abstract class often contains abstract methods, though it
doesn’t have to
 Abstract methods consist of only methods declarations,

without any method body


public abstract class Vehicle
{
String name;
public String getName()
{ return name; } \\ method body

abstract public void move();


\\ no body!
Abstract Classes
An abstract class often contains abstract methods,
though it doesn’t have to
Abstract methods consist of only methods declarations,
without any
method body
The non-abstract child of an abstract class must
override the abstract methods of the parent
An abstract class cannot be instantiated
The use of abstract classes is a design decision; it helps
us establish common elements in a class that is too
Abstract Method
Inheritance allows a sub-class to override the
methods of its
super-class.
A super-class may altogether leave the
implementation details
of a method and declare such a method abstract:

abstract type name(parameter-list);

Two kinds of methods:


1)concrete – may be overridden by sub-classes
2)abstract – must be overridden by sub-classes
this definition and usage
The this keyword refers to the current object in a method or
constructor.
The most common use of the this keyword is to eliminate the
confusion between class attributes and parameters with
the same name (because a class attribute is shadowed by a
method or constructor parameter).
this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
Using this with a class attribute (x):
public class Main
{
int x;
// Constructor with a parameter
Main(int x)
{
this.x = x;
}
// Call the constructor
public static void main(String[] args)
{
Main myObj = new Main(5);
[Link]("Value of x = " + myObj.x);
}
}
super definition and usage
•The super keyword refers to superclass (parent) objects.
•It is used to call superclass methods, and to access the superclass
constructor.
•The most common use of the super keyword is to eliminate the
confusion between superclasses and subclasses that have methods
with the same name.
•To understand the super keyword, you should have a basic
understanding of Inheritance and Polymorphism.
Using super to call the superclass of Dog (subclass):
class Animal { // Superclass (parent)
public void animalSound() {
[Link]("The animal makes a sound");
}
}
class Dog extends Animal { // Subclass (child)
public void animalSound() {
[Link](); // Call the superclass method
[Link]("The dog says: bow wow");
}
}
public class Main {
public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
[Link](); // Call the method on the Dog
object
}
}

You might also like