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

Inheritance Unit 2

Inheritance in Java is a key object-oriented design technique that allows developers to create new classes based on existing ones, facilitating code reuse and the establishment of class hierarchies. It includes concepts such as single, multi-level, and hierarchical inheritance, as well as the use of the 'protected' modifier for member visibility. Proper design for inheritance is crucial for maintainability and flexibility in software development.

Uploaded by

saradha.r
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)
5 views

Inheritance Unit 2

Inheritance in Java is a key object-oriented design technique that allows developers to create new classes based on existing ones, facilitating code reuse and the establishment of class hierarchies. It includes concepts such as single, multi-level, and hierarchical inheritance, as well as the use of the 'protected' modifier for member visibility. Proper design for inheritance is crucial for maintainability and flexibility in software development.

Uploaded by

saradha.r
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
You are on page 1/ 55

Inheritance in java

Inheritance
• Inheritance is a fundamental object-oriented
design technique used to create and organize
reusable classes
• Focuses on:
 deriving new classes from existing classes
 the protected modifier
 creating class hierarchies
 abstract classes
 indirect visibility of inherited members
 designing for inheritance
Outline
Creating Subclasses
Overriding Methods
Class Hierarchies
Inheritance and Visibility
Designing for Inheritance
Inheritance
• Inheritance allows a software developer to
derive 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 by the parent class
Inheritance
• Inheritance relationships are shown in a UML
class diagram using a solid arrow with an
unfilled triangular arrowhead pointing to the
parent class
Vehicle

Car

• Proper inheritance creates an is-a relationship,


meaning the child is a more specific version of
the parent
Inheritance
• A programmer can tailor a derived class as
needed by adding new variables or methods, or
by modifying the inherited ones
• Software reuse is a fundamental benefit of
inheritance
• By using existing software components to
create new ones, we capitalize on all the effort
that went into the design, implementation, and
testing of the existing software
Deriving Subclasses
• In Java, we use the reserved word extends to
establish an inheritance relationship

Class VEHICLE extends CAR


{
// class contents
}
Deriving Subclasses

class Animal
{
// eat() method
// sleep() method
}
class Dog extends Animal
{
// bark() method
}
Deriving Subclasses
Deriving Subclasses

is-a relationship
Inheritance is an is-a relationship. We use
inheritance only if an is-a relationship is present
between the two classes.

Here are some examples:


• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
TYPES OF INHERITANCE

• SINGLE INHERITANCE
• MULTIPLE INHERITANCE(Not supported in Java)
• MULTI LEVEL INHERITANCE
• HIERARCHICAL
• HYBRID INHERITANCE(Not supported in Java)
TYPES OF INHERITANCE
• SINGLE INHERITANCE

In Single Inheritance one class extends another class (one class


only).

In above diagram, Class B extends only Class A. Class A is a


super class and Class B is a Sub-class.
Types of Inheritance

• MULTIPLE INHERITANCE

In Multiple Inheritance, one class extending more than one class.


Java does not support multiple inheritance.
TYPES OF INHERITANCE

• MULTI LEVELINHERITANCE

In Multilevel Inheritance, one class can inherit from a derived


class. Hence, the derived class becomes the base class for the
new class.
TYPES OF INHERITANCE

• HIERARCHICAL INHERITANCE

In Hierarchical Inheritance, one class is inherited by many sub


classes.

As per above example, Class B, C, and D inherit the same class A.


TYPES OF INHERITANCE

• HYBRID INHERITANCE

Hybrid inheritance is a combination of Single and Multiple


inheritance
Single Inheritance : Example
class Animal {
public void eat() { System.out.println("I can eat"); }
public void sleep()
{ System.out.println("I can sleep"); } }
class Dog extends Animal
{
public void bark()
{
System.out.println("I can bark");
}}
class Main { public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.eat();
dog1.sleep();
dog1.bark(); } }
Output
I can eat
I can sleep
public class Dictionary extends Book
{
private int definitions = 52500;
// Prints a message using both local and inherited
values.
public double computeRatio ()
{
return definitions/pages;
}
// Definitions mutator.
public void setDefinitions (int numDefinitions)
{
definitions = numDefinitions;
}
// Definitions accessor.
public int getDefinitions ()
{
return definitions;
}
}
MULTI LEVEL INHERITANCE
• class Car{ public Car()
{ System.out.println("Class Car"); }
public void vehicleType()
{ System.out.println("Vehicle Type: Car");
}}
class Maruti extends Car
{ public Maruti() {
System.out.println("Class Maruti"); }

public void brand()


{ System.out.println("Brand: Maruti"); }
public void speed()
{ System.out.println("Max: 90Kmph"); }
}
public class Maruti800 extends Maruti{
public Maruti800() {
System.out.println("Maruti Model: 800"); }
public void speed() {
System.out.println("Max: 80Kmph"); }
MULTI LEVEL INHERITANCE
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}}

Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

© 2004 Pearson Addison-Wesley. All rights reserved 8-20


HIERARCHICAL INHERITANCE
class A { public void methodA() { System.out.println("method of
Class A"); } }
class B extends A { public void methodB()
{ System.out.println("method of Class B"); } }
class C extends A { public void methodC()
{ System.out.println("method of Class C"); } }
class D extends A { public void methodD()
{ System.out.println("method of Class D"); } }

class JavaExample {
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D(); //All classes can access the method
of class A
obj1.methodA();
obj2.methodA();
obj3.methodA(); } }
HIERARCHICAL INHERITANCE
• Output:
• method of Class A
• method of Class A
• method of Class A
The protected Modifier
• Visibility modifiers affect the way that class
members can be used in a child class
• Variables and methods declared with private
visibility cannot be referenced by name in a
child class
• They can be referenced in the child class if they
are declared with public visibility -- but public
variables violate the principle of encapsulation
• There is a third visibility modifier that helps in
inheritance situations: protected
The protected Modifier
• The protected modifier allows a child class to
reference a variable or method directly in the
child class
• It provides more encapsulation than public
visibility, but is not as tightly encapsulated as
private visibility
• A protected variable is visible to any class in the
same package as the parent class
• Protected variables and methods can be shown
with a # symbol preceding them in UML diagrams
The protected Modifier
Here's a summary from where access modifiers can
be accessed.

Class Package subclass World


public Yes Yes Yes Yes
private Yes No No No
protected Yes Yes Yes No
The protected Modifier
class Animal {
protected String type;
private String color;
public void eat()
{ System.out.println("I can eat");
}
public void sleep()
{ System.out.println("I can sleep");
} public String getColor()
{
return color;
}
public void setColor(String col)
{ color = col; }
}
The protected Modifier
class Dog extends Animal
{
public void displayInfo(String c)
{
System.out.println("I am a " + type);
System.out.println("My color is " + c);
}
public void bark() { System.out.println("I can bark"); }
}
class Main { public static void main(String[] args)
{ Dog dog1 = new Dog();
dog1.eat(); dog1.sleep(); dog1.bark();
dog1.type = "mammal"; dog1.setColor("black");
dog1.displayInfo(dog1.getColor()); } }
• Output
• I can eat
• I can sleep
• I can bark
• I am a mammal
• My color is black

© 2004 Pearson Addison-Wesley. All rights reserved 8-28


The super Reference
• Constructors are not inherited, even though they
have public visibility
• The super reference can be used to refer to the
parent class, and often is used to invoke the
parent's constructor
The super Reference
• A child’s constructor is responsible for calling
the parent’s constructor
• The first line of a child’s constructor should use
the super reference to call the parent’s
constructor
• The super reference can also be used to
reference other variables and methods defined
in the parent’s class
Experiment
public class ParentClass {
public ParentClass() {
System.out.println("In ParentClass constructor");
}
}
public class SubClass1 extends ParentClass {
public SubClass1() {
System.out.println("In SubClass1 constructor");
}
}
public class SubClass2 extends ParentClass {
public SubClass2() {
super();
System.out.println("In SubClass2 constructor");
}
}
Output: Creating an instance of SubClass1
In ParentClass constructor
In SubClass1 constructor

Creating an instance of SubClass2


In ParentClass constructor
In SubClass2 constructor 8-31
Outline
Creating Subclasses
Overriding Methods
Class Hierarchies
Designing for Inheritance
Overriding Methods
• A child class can override the definition of an
inherited method in favor of its own
• The new method must have the same signature
as the parent's method, but can have a different
method defnition
• The type of the object executing the method
determines which version of the method is
invoked
Overriding
• A method in the parent class can be invoked
explicitly using the super reference
• If a method is declared with the final modifier,
it cannot be overridden
• The concept of overriding can be applied to data
and is called shadowing variables
• Shadowing variables should be avoided
because it tends to cause unnecessarily
confusing code
Overloading vs. Overriding
• Overloading deals with multiple methods with
the same name in the same class, but with
different signatures
• Overriding deals with two methods, one in a
parent class and one in a child class, that have
the same signature
• Overloading lets you define a similar operation
in different ways for different parameters
• Overriding lets you define a similar operation in
different ways for different object types
FoodItem.java
public class FoodItem
{
final private int CALORIES_PER_GRAM = 9;
private int fatGrams;
protected int servings;

//-------------------------------------------------------
---
// Sets up this food item with the specified number of
fat
// grams and number of servings.
//-------------------------------------------------------
---
public FoodItem (int numFatGrams, int numServings)
{
fatGrams = numFatGrams;
servings = numServings;
}
FoodItem.java
//-------------------------------------------------------
---
// Computes and returns the number of calories in this
food
// item due to fat.
//-------------------------------------------------------
---
private int calories()
{
return fatGrams * CALORIES_PER_GRAM;
}

//-------------------------------------------------------
---
// Computes and returns the number of fat calories per
// serving.
//-------------------------------------------------------
---
public int caloriesPerServing()
{
return (calories() / servings);
}
}
Pizza.java
public class Pizza extends FoodItem
{
//-------------------------------------------------------
---
// Sets up a pizza with the specified amount of fat
// (assumes eight servings).
//-------------------------------------------------------
---
public Pizza (int fatGrams)
{
super (fatGrams, 8);
}
}
FoodAnalyzer.java
public class FoodAnalyzer
{
//-------------------------------------------------------
---
// Instantiates a Pizza object and prints its calories
per
// serving.
//-------------------------------------------------------
---
public static void main (String[] args)
{
Pizza special = new Pizza (275);

System.out.println ("Calories per serving: " +


special.caloriesPerServing());
}
}
Outline
Creating Subclasses
Overriding Methods
Class Hierarchies
Inheritance and Visibility
Designing for Inheritance
Class Hierarchies
• A child class of one parent can be the parent of
another child, forming a class hierarchy

Business

RetailBusines ServiceBusine
s ss

KMart Macys Kinkos


Class Hierarchies
• Two children of the same parent are called
siblings
• Common features should be put as high in the
hierarchy as is reasonable
• An inherited member is passed continually down
the line
• Therefore, a child class inherits from all its
ancestor classes
• There is no single class hierarchy that is
appropriate for all situations
The Object Class
• A class called Object is defined in the
java.lang package of the Java standard class
library
• All classes are derived from the Object class
• If a class is not explicitly defined to be the child
of an existing class, it is assumed to be the child
of the Object class
• Therefore, the Object class is the ultimate root
of all class hierarchies
The Object Class
• The Object class contains a few useful
methods, which are inherited by all classes
• For example, the toString method is defined in
the Object class
• Every time we define the toString method, we
are actually overriding an inherited definition
• The toString method in the Object class is
defined to return a string
The Object Class
• The equals method of the Object class returns
true if two references are aliases
• We can override equals in any class to define
equality in some more appropriate way
• As we've seen, the String class defines the
equals method to return true if two String
objects contain the same characters
• The designers of the String class have
overridden the equals method inherited from
Object in favor of a more useful version
Outline

Creating Subclasses
Overriding Methods
Class Hierarchies
Designing for Inheritance
Designing for Inheritance
• As we've discussed, taking the time to create a
good software design reaps long-term benefits
• Inheritance issues are an important part of an
object-oriented design
• Properly designed inheritance relationships can
contribute greatly to the elegance,
maintainability, and reuse of the software
• Let's summarize some of the issues regarding
inheritance that relate to a good software design
Inheritance Design Issues
• Every derivation should be an is-a relationship
• Think about the potential future of a class
hierarchy, and design classes to be reusable
and flexible
• Find common characteristics of classes and
push them as high in the class hierarchy as
appropriate
• Override methods as appropriate to tailor or
change the functionality of a child
• Add new variables to children, but don't redefine
(shadow) inherited variables
Inheritance Design Issues
• Allow each class to manage its own data; use
the super reference to invoke the parent's
constructor to set up its data
• Even if there are no current uses for them,
override general methods such as toString
and equals with appropriate definitions
• Use abstract classes to represent general
concepts that lower classes have in common
• Use visibility modifiers carefully to provide
needed access without violating encapsulation
Restricting Inheritance
• The final modifier can be used to curtail
inheritance
• If the final modifier is applied to a method,
then that method cannot be overridden in any
descendent classes
• If the final modifier is applied to an entire
class, then that class cannot be used to derive
any children at all
 Thus, an abstract class cannot be declared as final

• These are key design decisions, establishing


that a method or class should be used as is
ABSTRACT CLASSES
• A class which is declared with the abstract
keyword is known as an abstract class in Java.
It can have abstract and non-abstract
methods (method with the body).
• Abstraction in Java
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.

© 2004 Pearson Addison-Wesley. All rights reserved 8-51


• Another way, it shows only essential things to
the user and hides the internal details, for
example, sending SMS where you type the
text and send the message. You don't know
the internal processing about the message
delivery.
• Abstraction lets you focus on what the object
does instead of how it does it.
• Ways to achieve Abstraction
• There are two ways to achieve abstraction in
java
1. Abstract class (0 to 100%)
2. Interface (100%)

© 2004 Pearson Addison-Wesley. All rights reserved 8-52


• An abstract class must be declared with an
abstract keyword.
• It can have abstract and non-abstract
methods.
• It cannot be instantiated.
• It can have constructors and static methods
also.
• It can have final methods which will force the
subclass not to change the body of the
method.
• Example of abstract class
abstract class A{}

© 2004 Pearson Addison-Wesley. All rights reserved 8-53


• Abstract Method in Java
• A method which is declared as abstract and
does not have implementation is known as an
abstract method.
• Example of abstract method
abstract void printStatus();//
no method body and abstract

© 2004 Pearson Addison-Wesley. All rights reserved 8-54


EXAMPLE
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

© 2004 Pearson Addison-Wesley. All rights reserved 8-55

You might also like