inheritance_assignment
inheritance_assignment
• Code Reusability: Avoids redundancy by allowing subclasses to reuse parent class code.
• Extensibility: New functionalities can be added to subclasses without modifying the parent
class.
class Animal {
d.bark();
Dog barks.
(b) Multilevel Inheritance
class Animal {
p.weep();
class Animal {
p.weep();
Dog barks.
Puppy weeps.
class Animal {
d.eat();
d.bark();
c.eat();
c.meow();
Cat meows.
Since Java does not support multiple inheritance through classes, Hybrid inheritance is implemented
using interfaces.
Multiple inheritance occurs when a class inherits from more than one class. Java does not support
multiple inheritance using classes to avoid the Diamond Problem.
Diamond Problem:
If two parent classes have the same method and the child class inherits from both, there is ambiguity
about which method to execute.
class A {
class B {
interface A {
void show();
interface B {
void display();
class C implements A, B {
obj.show();
obj.display();
Method overriding occurs when a subclass provides a specific implementation of a method already
defined in its superclass.
1. The method in the subclass must have the same signature (name and parameters) as in the
superclass.
2. The method in the subclass should have the same return type (or a subclass of the return
type in Java 5+).
3. The access modifier of the overriding method cannot be more restrictive than the superclass
method.
class Animal {
@Override
Method overriding occurs when a subclass provides a specific implementation of a method already
defined in its superclass.
1. The method in the subclass must have the same signature (name and parameters) as in the
superclass.
2. The method in the subclass should have the same return type (or a subclass of the return
type in Java 5+).
3. The access modifier of the overriding method cannot be more restrictive than the superclass
method.
Example:-
class Animal {
@Override
OUTPUT:- 15
7.7
}
class Child extends Parent {
@Override