WHAT'S NEW?

Private Method Cannot be Overriden

Before starting up with the concept of overriding let us have a look on working on private access specifier.

Private Access

When a method or a variable is declared as private its scope is limited to class itself. 
In simple word when something in class is private it is accessible from same class and from no where else, not even class in same package or its sub classes.

Private Method Cannot be Overridden


A method declared final in a class is available only in the same class itself.

Let say i have a class by name SuperClass

class SuperClass
{

public void m1()
{
System.out.println("Super Class-m1()");
}
//Private Method
private void m2()
{
System.out.println("Super Class-m2()");
}

}

This class will look like this in memory structure.





Now let us design a class by name SubClass which extends SuperClass and inherits its variables and methods.

class SubClass extends SuperClass
{
public void m3()
{
System.out.println("Sub Class-m3()");
}
public void m2()
{
System.out.println("Sub Class-m2()");
}

public void m4()
{
System.out.println("Sub Class-m4()");
}

}

This class will look like this in memory structure.



Upper part of the memory shows the inherited methods so if we observe m2() never got inherited because of its private access.

"Hence if the super class have a private method and then sub class have  method with the same signature , it is just a Coincidence and not Overriding."





0 comments:

Post a comment