Inheritance and Polymorphism
Inheritance:
Inheritance is one of the core concepts of object-oriented programming. It allows a class (subclass/child class) to inherit properties and behaviors from another class (superclass/parent class). Inheritance promotes code reuse and establishes relationships between classes.
Syntax of Inheritance:
Example of Inheritance in Java:
In this example, the Dog
class is a subclass of the Animal
class. Dog
inherits the sound()
method from Animal
. If you create a Dog
object and call sound()
, it will print "Dog barks".
Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility in programming by allowing methods to work with objects of any subclass of the declared type. Java supports two types of polymorphism: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding).
Runtime Polymorphism (Method Overriding):
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It allows a subclass to provide a specialized version of a method that is already defined in its superclass.
Example of Method Overriding:
In this example, the sound()
method in the Dog
class overrides the sound()
method in the Animal
class. When you call sound()
on a Dog
object, it prints "Dog barks" instead of "Animal makes a sound".
Example with Polymorphism:
In this example, myDog
is declared as an Animal
type but is actually referring to a Dog
object. This is an example of polymorphism. When sound()
is called, it invokes the overridden method in the Dog
class, demonstrating runtime polymorphism. This flexibility simplifies code and allows for more dynamic behavior in Java programs.
Last updated