During inheritance, which will be inherited - public, private, protected attributes and methods?

Need:

In object-oriented programming, inheritance allows a class (child) to reuse and extend the properties and behaviors of another class (parent). However, not all attributes and methods are inherited in the same way. If access modifiers are not properly understood, it may lead to unintended behavior, limiting code reuse or exposing sensitive data.

What is it?

Inheritance is a mechanism in which a child class derives properties and methods from a parent class. The accessibility of inherited members depends on their access modifiers:

Public: Accessible everywhere. Private: Restricted to the same class, not inherited.

Protected: Inherited and accessible within child classes.How is it used?*

By understanding which attributes and methods get inherited, developers can design robust and reusable class hierarchies. For example, protected methods can be overridden in a subclass, while private attributes remain encapsulated within the parent class.

Answer:

During inheritance:

1. Public members (attributes \& methods) → Inherited and accessible in the child class and other classes.

2. Private members (attributes \& methods) → Not inherited directly by the child class. However, they can be accessed through getter and setter methods if provided.

3. Protected members (attributes \& methods) → Inherited and accessible within the child class but not from outside the hierarchy.

   class Parent {

public int publicVar = 10;

private int privateVar = 20;

protected int protectedVar = 30;

public void publicMethod() {

   System.out.println("Public method");

}

private void privateMethod() {

   System.out.println("Private method");

}

protected void protectedMethod() {

   System.out.println("Protected method");

}


}

class Child extends Parent {

void display() {

   System.out.println(publicVar);  // Inherited

// System.out.println(privateVar); // Not accessible (Compile-time error)

System.out.println(protectedVar); // Inherited

publicMethod(); // Inherited

// privateMethod(); // Not accessible (Compile-time error)

protectedMethod(); // Inherited

}


}

public class Main {

public static void main(String[] args) {

   Child obj = new Child();

obj.display();

}


}

Key Takeaways:

  • Public members → Inherited and accessible.
  • Private members → Not inherited.
  • Protected members → Inherited but accessible only within the subclass.