Simple inheritance example

public class Test {
	
	public static void main(String[] args)
	{
		MoreSpecificCat moreSpecificCat = new MoreSpecificCat();
		System.out.println(moreSpecificCat.numberOfLegs);
		moreSpecificCat.getName();
		moreSpecificCat.showNumberOfLegs();
		
	}
}


class Cat // the SUPERCLASS
{
	int numberOfLegs=4;
	
	public int getNumberOfLeg()
	{
		return numberOfLegs;
	}
	
	public void showNumberOfLegs()
	{
		System.out.println(numberOfLegs);
	}
}

class MoreSpecificCat extends Cat // the SUBCLASS
{
	String name="Star";
	
	public void getName()
	{
		System.out.println(name);
	}
	
}

Output:

4
Star
4

Important: The subclass CANNOT access PRIVATE variables and methods of the superclass

Leave a Reply