This week's giveaway is in the Programmer Certification (OCPJP) forum.
We're giving away four copies of Java Mock Exams (software) and have David Mayer on-line!
See this thread for details.
Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) 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
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!