• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

override and overload methods

 
Sharu Biks
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,This is the first post that im making to this forum and hope to get a solution for my confusion.

class Parent
{
private 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[])
{
Parent p = new Child();
p.method2();
}
}


The output of the above program is
parents method2(),parents method1().

If the access modifier of the method1 in parent class is changed to public then the output is
parents method2() and childs method1()

But if the access modifier of the method1() in child class is made private even then parent method1() is called

can any one please explain me how the process is taking place.

Thanks in advance
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its quite simple. If you have a private method in your parent class it means you can't over-ride it. Now you may ask the question like, "Why it is not giving any compile time error like can not over-ride the private method". So, the answer would be if the method is private in parent class it means child class can't see that. If a child try to over-ride that method then it simply means client has its own method with the same names, signatures and return type as parent has, thats it.

If you cant see it you can't over-ride it.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not a J2ME specific question, though. Should be in Java General Beginner forum.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic