Java Inheritance Concepts - Summary and Program
1. Member Access and Inheritance
When a class inherits from another, it gets access to all non-private members (fields and methods).
Private members are not inherited, but can be accessed via public/protected methods.
2. Multilevel Inheritance
A class inherits from another class, which in turn inherits from a third class.
Example:
class A {}
class B extends A {}
class C extends B {}
3. super Keyword
Used to call the parent class constructor or access parent class methods/variables.
Example:
super();
super.name;
super.display();
4. final Keyword
Used to:
- Make a variable constant
- Prevent method overriding
- Prevent class inheritance.
Example:
final int x = 10;
final void show() {}
final class A {}
5. Method Overriding
Java Inheritance Concepts - Summary and Program
Subclass defines a method with the same name/signature as in the parent.
Achieves runtime polymorphism.
6. Dynamic Method Dispatch
Superclass reference refers to a subclass object.
At runtime, the overridden method of the actual object is called.
7. Abstract Classes and Methods
Abstract class: cannot be instantiated.
Abstract method: must be overridden in subclass.
Example:
abstract class Animal { abstract void sound(); }
Java Program Example
abstract class Animal {
String name = "Animal";
abstract void sound();
void sleep() {
System.out.println(name + " sleeps...");
class Dog extends Animal {
String name = "Dog";
void sound() {
System.out.println("Dog barks");
void showNames() {
System.out.println("Subclass name: " + name);
Java Inheritance Concepts - Summary and Program
System.out.println("Superclass name: " + super.name);
class Puppy extends Dog {
final int age = 1;
void sound() {
System.out.println("Puppy yelps");
final void eat() {
System.out.println("Puppy eats puppy food");
public class Main {
public static void main(String[] args) {
Animal a;
a = new Puppy();
a.sound();
a.sleep();
Puppy pup = new Puppy();
pup.showNames();
pup.eat();