Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Overidden functions

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I couldn't understand properly the ans to this quest.

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();
}
}

Ans o/p is
Parent's method2();
Parent's method1();
I understand that private methods are not inherited and not overridden. Still i was expecting "Child's method1()" to be printed. When p.method2()(then inheritted method2)is called, a this pointer is passed which points to Child's object. Child doesn't know anything about the super classes method1(), but then the ans......I think I am making a blunder somewhere. Pls help me in this.
Also if u could give some link on this...
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi meeta,
Because the Child does not override the method1() in Parent, method1() in Child class and method1() in Parent is two different methods, so, the Parent.method2() just call it's(class Parent's) own method1(), this is because the method1() exists in Parent and it is not be overrided;
 
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since the private method cannot be overridden, the two methods act as two individual methods...Try putting protected in place of private ..then the result u expected will come.
Try reading about accessibility and overridden methods topics.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic