Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance

 
Johnson David
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question for all, regarding inheritance

take a look at the fallowing code

class Parent
{
public void method1()
{
System.out.println("Parent's method1()");
}
public void method2()
{
System.out.println("Parent's method2()");
method1();
}
}
class Child extends Parent
{
public void method1()
{
System.out.println("Child's method1()");
}
public static void main(String args[])
{
Child p = new Child();
p.method2();
}
}

the output of the above code is

Parent's method2()
Child's method1()

this is ok ,

but i will make a small change in the above code , i replace

"private" in place of "public" in method1() of parent class , output of

the code after the changes are

Parent's method2()
Parent's method1()

private means, it should not be accessible from the subclass,

but why the output is comming like this, can anybody explain me?
 
Nischal Tanna
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private member is not accessible to a child class !!!... its only accessible within the class.. Also, if u change from public to private, the method method1() cannot be overriden since it is not available to the child... It can be just hidden...Hope this helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic