[Go to site: main page, start]

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

Java Inheritance and Polymorphism Explained

The document explains the concept of inheritance in Java, detailing various types such as single, multilevel, multiple, and hierarchical inheritance. It also covers method overriding, interfaces, and polymorphism, including compile-time and runtime polymorphism. Additionally, it discusses the use of the final keyword, the finally block, and the super keyword in Java programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views20 pages

Java Inheritance and Polymorphism Explained

The document explains the concept of inheritance in Java, detailing various types such as single, multilevel, multiple, and hierarchical inheritance. It also covers method overriding, interfaces, and polymorphism, including compile-time and runtime polymorphism. Additionally, it discusses the use of the final keyword, the finally block, and the super keyword in Java programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit 3

Inheritance:- when we construct a new class from


existing class in such a way that the nwew class
access all the features & properties of existing
class.
 In java extends keyword is used to perform
inheritance.
 It provides code reusability
 We cannot access private members of class through
inheritance.
 A sub class contains all the features of super class so,
we should create the object of sub class
 Method overriding oonlyb possible through method
overloading.

Syntax:-
Class A//super class
{
}
Class B extends A//sub class
{ }
Types of inheritance
[Link]/simple inheritance :-it contain only one
superclass and one [Link] subclass n is cannot
connect directly with superclass it connected firstly
previous subclass.
[Link] inheritance :-it contain more than one
subclass but only one super class.
[Link] inheritance:- java does not support multiple
inheritance because it has two superclasses and only one
subclasses
[Link] inheritance:- it contain more than one
subclass but only one super class. But in this type subclass
is directly connect with super class

Single inheritance

Syntax:-
Class A//super class
{
}
Class B extends A//sub class
{ }

Example program…..
class student //super class
{
int roll,marks;
String name;
void input()
{
[Link]("enter roll no & name & marks : ");
}
}
class nikita extends student //sub class
{
void disp()
{
roll=15; name="nikita"; marks=90;
[Link](roll+" "+name+" "+marks);
}
public static void main(String[] args)
{
nikita n=new nikita();
[Link](); [Link]();
}
}

Output:-

Multi-level inheritance…
Syntax :-
Class super
{
}
Class sub1 extends super
{
}
Class sub2 extends sub1
{
}

Example program….
class A //super class
{
int a,b,c;
void add() //method
{
a=10;b=20;
c=a+b;
[Link]("addition of two numbers is "+c);
}

void sub()
{
a=100;b=200;
c=a-b;
[Link]("substraction of two numbers is "+c);
}
}
class B extends A //sub class 1
{
void mul()
{
a=10;b=20;
c=a*b;
[Link]("multiplication of two numbers is "+c);
}
void div()
{
a=100;b=2;
c=a/b;
[Link]("division of two numbers is "+c);
}
}
class C extends B //sub class 2
{
void rem()
{
a=10;b=2;
c=a%b;
[Link]("reminder of two numbers is "+c);
}
}
class Test1 //main class…
{
public static void main(String[] args)
{
C r=new C(); //creating object
[Link]();
[Link](); //method calling
[Link]();
[Link]();
[Link]();
}
}
Output:-

Multilevel inheritance :- whenever a subclass wants to


inherit the property of two or more super class that hava
same method,java compiler cant decide which class
method it should inherit.
Then their might be a chance of memory duplication that
is ,java does not support…………..multiple inheritance.
Synatax:-
Class A
{
Void m1()
{
}}
Class B
{
Void m1()
{
}
Class C extends A,B
{
C is in confusion they doesn’t decide which class they will
have to extend
}

What is interface?
Interface is just like a class,which contains only abstract
method .
To achieve interface in java it provides a keyword called
implements…..

 Multiple inheritance using interface


We can achieve multiple inheritance through interfaces
because interface contains only abstract method ,which
implementation is provided by the sub class.
Class C extends A,B //invalid
Class C implements A,B // valid…
Creating interface
Syntax:-
Interface interface name
Example:-
interface A
{
void show();
}
interface B
{
void show();
}
class multiple implements A,B
{
public void show()
{
[Link]("Interface A & B");
}
public static void main(String[] args)
{
multiple m=new multiple();
[Link]();
}
}

Output:-

Hierarchical inheritance….
Syntax :_
Class A
{
}
Class B extends A
{
}
Class C extends A
{
}
Example program…..
class A
{
void show()
{
[Link]("hello guys");
}
}
class B extends A
{
void disp()
{
[Link]("Welcome guys");
}
}
class C extends A
{
void play()
{
[Link]("good night");
}
}
class Demo1
{
public static void main(String[] args)
{
B a=new B();
C a1=new C();
A a2=new A();
[Link]();
[Link]();
[Link]();
}
}

Output:-

 Compile time polymorphism


A polymorphism which is exist at the time of compilation is called
as compile time polymorphism or early binding polymorphism or
static polymorphism.

Example:-
Method Overloading:-
Whenever class contain more than one
method with same name and different types of parameters is
called as method overloading…
Syntax:-
Return_type method_name(para1);
Return_type method_name(para1,para n);
Void display(int a);

Example:-

Output:-
Runtime polymorphism
A polymorphism which exists at the time of execution of the
program is called as runtime polymorphism..
Example..
Method overriding
Whenever we writing a method name in
super class and sub classes in such a way that the method name
and parameter must be same is called as method overriding..
We cannot perform method overriding without inheritance.
Syntax:-
Class A
{
void show()
{
}
}
Class B extends A
{
Void show()
{
}
}
Output:-

 Dynamic method dispatch


 Dynamic method is also called as a runtime
polymorphism
 Dynamic method dispatch is a mechanism that decides
which overridden method will be called at runtime.

Final ,finally, finalize


Final is a keyword which we can apply with
variable ,method and class.
Example…
Final int a=10;
In the case of final method we can not override the
method …
In the case of final class we cannot create the extends any
class means we cannot create subclass or child class this
must be only final class..

Finally
Finally is a block which is used in in try catch block .
This block is must be execute in try catch block if the
exception is handled or not this block must be executed.
Syntax:-
Try
{
}
Catch{
//handeling code
}
Finally
{
Clean up code;
}

Finalize method
Finalize{}
Finalize is a method
It is used to deallocate the resources which is allocated by
unused object

 Super keyword
Super keyword refers to the objects of super class,it is used
when we want to call the super class variable ,method &
constructor through sub class object.
Whenever the super class & sub class variable and method
name both are same than it can be used only
To avoid the confusion between super class and sub
classes variables & methods thatc have same name we
should use super keyword…
Using super keyword we can access super class
variable ,method and constructor.


Output:-

Common questions

Powered by AI

Method overriding is fundamental to achieving runtime polymorphism in Java, allowing a subclass to provide a specific implementation of a method declared in its superclass . This dynamic method dispatch mechanism determines which method implementation to execute at runtime, enabling flexible and configurable code behavior. Constraints of method overriding include the need for the method names and parameter lists to match exactly in both superclass and subclass, and overriding cannot occur with 'final' methods . These constraints ensure consistency and prevent unintended behavior changes across the inheritance hierarchy.

Java does not support multiple inheritance through classes to avoid ambiguity and complexity arising from the diamond problem, where a subclass could inherit method signatures from more than one superclass, leading to conflict in method calls . Instead, Java allows multiple inheritance through interfaces, as interfaces only declare method signatures and leave their implementation to the implementing classes. This design allows a class to implement multiple interfaces and provide the necessary method implementations, thus achieving multiple inheritance without the issues faced by class-based inheritance .

The 'final' keyword, the 'finally' block, and the 'finalize' method serve distinct purposes in Java. 'Final' is used to declare constants once a value is assigned, prevent method overriding, and ensure a class cannot be subclassed . The 'finally' block is associated with try-catch statements to execute code regardless of exception handling, ensuring certain operations run, such as resource cleanup . 'Finalize' is a method used for garbage collection, allowing an object to release resources before being deallocated . Each serves a unique function related to resource management and code safety.“

Dynamic method dispatch is crucial for Java's runtime polymorphism, allowing the JVM to determine which overridden method to call at runtime based on the object's actual type . This mechanism supports method overriding by enabling different subclass implementations of a method, even if the superclass and subclass methods have identical signatures. Thus, while the superclass references an object, the overridden subclass method is executed, ensuring flexible and dynamic program behavior . This approach allows for clean and efficient memory use and application customization.

A Java interface is similar to a class but only includes abstract methods without implementation. It allows multiple inheritance by enabling a class to implement multiple interfaces, thereby inheriting their abstract method signatures without the complications associated with class-based multiple inheritance . For example, a class can implement both interfaces A and B, inheriting methods to be implemented by the class, thus bypassing the diamond problem inherent in multiple class inheritance .

Method overloading achieves compile-time polymorphism by allowing multiple methods with the same name but different parameter types or numbers within a class . This lets the Java compiler resolve which method to invoke based on the method signature at compile time, rather than at run time. For instance, if a class has methods `void display(int a)` and `void display(String b)`, calling `display(10)` invokes the first method while `display('Hello')` invokes the second . This flexibility enhances code readability and maintainability.

Hierarchical inheritance involves multiple subclasses inheriting from a single superclass. For example, in the given code, class A is the superclass while classes B and C are direct subclasses of A, each inherit A's methods independently, like the method `show` . This structure supports code reuse and method specialization across multiple related classes . Hierarchical inheritance is suitable when common functionality must be shared across different classes that do not relate to each other through a common subclass.

The 'super' keyword in Java is used within a subclass to refer to its immediate superclass. It helps access superclass methods, variables, and constructors, particularly when the superclass and subclass have identical method names or variables . By using 'super', a programmer avoids name conflicts and ensures the correct superclass method or variable is accessed, enhancing code clarity and maintaining proper inheritance behavior in complex hierarchies .

Multilevel inheritance involves a superclass and multiple layers of subclasses, each inheriting from the preceding subclass, forming a hierarchy . For example, in the provided code, class A (superclass) is extended by class B, which is further extended by class C. This allows class C to inherit methods from both class A and class B. The methods `add`, `sub`, `mul`, `div`, and `rem` demonstrate how inherited methods can be accessed and used in the subclass .

Inheritance in Java promotes code reuse by allowing a new class to inherit properties and behaviors of an existing class, thus reducing redundancy . It improves code maintainability as changes in the superclass can propagate to subclasses without needing additional modifications. However, private members of the superclass remain inaccessible, maintaining encapsulation . This structure aids in managing larger codebases by promoting organized and modular code architecture.

You might also like