Inheritance Example - A Derived Class

Contact Us or call 1-877-932-8228
Inheritance Example - A Derived Class

Inheritance Example - A Derived Class

When a derived class is created, an object of the new class will in effect contain all the members of the base and derived classes. In some cases, the accessibility modifiers can limit base class members availability in the derived class, but we will cover that issue later.

The following maps out the relation between the derived class and the base class (note that the diagrams show the apparent memory allocation, in a real implementation the base class memory block is not inside the derived class block).

Class Code Apparent Memory Allocation
public class MyBase {
	public int x;
	public void show() {
		System.out.println("x =" + x);
}
MyBase memory structure
class MyDerived extends MyBase {
	public int y;
	public void show() {
		System.out.println("x = " + x);
		System.out.println("y = " + y);
	}
}
MyDerived memory structure

Since everything in MyBase is public, code in the MyDerived class has free access to the x value from the MyBase object inside it, as well as y and show() from itself.

The show() method from MyBase is also available, but only within MyDerived class code (but some work is required to get it, since it is hidden by the show() method added with MyDerived) - code in other classes cannot invoke the MyBase version of show() at all.

Next