0% found this document useful (0 votes)
24 views42 pages

Unit 3 Inheritance

The document provides an overview of inheritance and interfaces in Java, detailing concepts such as superclasses, subclasses, and the types of inheritance including single, multilevel, and hierarchical. It explains the significance of the Object class, abstract classes, and methods, as well as the use of interfaces for achieving abstraction and multiple inheritance. Additionally, it covers final methods and classes, emphasizing their immutability and restrictions on inheritance.

Uploaded by

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

Unit 3 Inheritance

The document provides an overview of inheritance and interfaces in Java, detailing concepts such as superclasses, subclasses, and the types of inheritance including single, multilevel, and hierarchical. It explains the significance of the Object class, abstract classes, and methods, as well as the use of interfaces for achieving abstraction and multiple inheritance. Additionally, it covers final methods and classes, emphasizing their immutability and restrictions on inheritance.

Uploaded by

kishorekannann82
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

Unit-3

INHERITANCE AND INTERFACES


Inheritance – Super classes - sub classes – Protected members –
constructors in sub classes – the Object class – abstract classes and
methods - final methods and classes – Interfaces – defining an interface,
implementing interface, differences between classes and interfaces and
extending interfaces- Object cloning inner classes, Array Lists – Strings.
Inheritance
Inheritance in Java
• Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent 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.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
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 defined in the previous
class.
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.
• In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Java Inheritance Example

Programmer is the subclass and Employee is the


superclass. The relationship between the two classes
is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
class Employee{
float salary=40000;
}

class Programmer extends Employee{


int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT
• Programmer salary is:40000.0
• Bonus of programmer is:10000
Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
• Single
• Multilevel
• Hierarchical
• Multiple
• Hybrid
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.
Output:
class Animal{
void eat(){System.out.println("eating...");} barking...
}
class Dog extends Animal{
eating...
void bark()
{
System.out.println("barking...");
}
}
public class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
public class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat(); }}
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(){System.out.println("eating...");} OUTPUT
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Why multiple inheritance is not supported in java?
• To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
• Consider a scenario where A, B, and C are three classes. The C class inherits A
and B classes. If A and B classes have the same method and you call it from child
class object, there will be ambiguity to call the method of A or B class.
• Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Thank you
Protected Member
• The private members of a class cannot be directly accessed outside the class.
• Only methods of that class can access the private members directly.
• Sometimes it may be necessary for a subclass to access a private member of a superclass.
• If you make a private member public, then anyone can access that member.
• So, if a member of a superclass needs to be (directly) accessed in a subclass and yet still prevent
its direct access outside the class, you must declare that member protected.
Protected Member

class A {

protected String msg="Try to access the protected variable outside the class within the package";

}
public class ProtectedExample2 {
public static void main(String[] args) {
A a=new A();
System.out.println(a.msg);

}
}
Object class in Java
• The Object class is the parent class of all the classes in java by default. In other words, it
is the topmost class of java.
• Let's take an example, there is getObject() method that returns an object but it can be of
any type like Employee,Student etc, we can use Object class reference to refer that object.
For example:
Object obj=getObject();
• The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
• The Object class provides many methods. They are as follows:
Method Description
returns the Class class object of this object. The
public final Class getClass() Class class can further be used to get the metadata
of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() returns the string representation of this object.

wakes up single thread, waiting on this object's


public final void notify()
monitor.
ABSTRACT CLASSES AND METHODS
Abstract class in Java
• 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.
• Another way, it shows only essential things to the user and hides the internal details.
Abstraction lets you focus on what the object does instead of how it does it.
Abstract class in Java
• A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented.
• Points to Remember
• 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.
Example of abstract class
abstract class A{}
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
Example of Abstract class that has an abstract method
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Understanding the real scenario of Abstract class
abstract class Shape Public class TestAbstraction1
{ {
abstract void draw();
} public static void main(String args[
class Rectangle extends Shape ])
{ {
void draw()
{
Shape s=new Circle1();
System.out.println("drawing rectangle");
} s.draw();
} }
class Circle1 extends Shape }
{
void draw()
{
System.out.println("drawing circle");
}
}
Interface in Java
• An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can
be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
Why use Java interface?
There are mainly three reasons to use
interface. They are given below.
•It is used to achieve abstraction.
•By interface, we can support the
functionality of multiple inheritance.
•It can be used to achieve loose coupling.
How to declare an interface?

• An interface is declared by using the interface keyword.


• It provides total abstraction; means all the methods in an interface are declared with
the empty body, and all the fields are public, static and final by default.
• A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
•As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an
interface.
Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
//Interface declaration: by first user
interface Drawable
{ //Using interface: by third user
void draw(); public class TestInterface1
} {
//Implementation: by second user public static void main(String args[])
class Rectangle implements Drawable {
{ Drawable d=new Circle();
public void draw() d.draw();
{ }
System.out.println("drawing rectangle"); }
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.
Example public static void main(String args[])
interface Printable {
{ A7 obj = new A7();
void print(); obj.print();
} obj.show();
interface Showable }
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

}
FINAL METHODS AND CLASSES.
Final variable, Method and Class
1) final variable
• final variables are nothing but constants.
• We cannot change the value of a final variable once it is initialized. Lets have a look at the below code:
class Demo
{
final int MAX_VALUE=99;
void myMethod()
{
MAX_VALUE=101;
}
public static void main(String args[])
{
Demo obj=new Demo();
obj.myMethod();
}}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Demo.MAX_VALUE cannot be assigned
2) Blank final variable
• a constructor is a special method used to initialize objects of a class. It has the same name as the
class, doesn't have a return type (not even void), and is automatically called when an object is
created using the new keyword.

• Yes, but only in constructor we can initialize blank variable


class Bike{
final int speedlimit;//blank final variable

Bike(){
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike();
}
}
2) final method
• A final method cannot be overridden. If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");} Output
}

class Honda extends Bike{


//We cannot override the final method
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
3) final class
We cannot extend a final class.
If you make any class as final, you cannot extend it. Output:
XYZ.java:4: error: cannot inherit from final XYZ
Consider the below example:
class ABC extends XYZ
final class XYZ ^
{ 1 error
} error: compilation failed
class ABC extends XYZ
{
void demo()
{
System.out.println("My Method");
}
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo(); } }

You might also like