• 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
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

out put of class

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can any body explain the out put as iam getting answer 2 ;
* but answer is 1;
public class Poly
{
public static void main(String argc[])
{
A ref1=new C();
B ref2=(B)ref1;
System.out.println(ref2.g());
}
}
class A
{
private int f() {return 0; }
public int g() {return 3; }
}
class B exends A {
private int f() { return 1;}
public int g() { return f(); }
}
class C extends B {
public int f() { return 2; }
}
 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by gouru:
can any body explain the out put as iam getting answer 2 ;
* but answer is 1;
public class Poly
{
public static void main(String argc[])
{
A ref1=new C();
B ref2=(B)ref1;
System.out.println(ref2.g());
}
}
class A
{
private int f() {return 0; }
public int g() {return 3; }
}
class B extends A {
private int f() { return 1;}
public int g() { return f(); }
}
class C extends B {
public int f() { return 2; }
}


I am using jdk1.2.2 and when this is ran, I get an output of 1. I thought the method that was chosen was based on the actual object? Could this result be because a B method made the call, it's method was chosen?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi
the basic thing is that in method g() u r calling a private method f(). Remember that private methods are not overriden. thus class C method f() is not called.
if u change the B.f() method to coderanch, protected, or default u will get the result that u expect.
if u have problems do tell me.
regds
Rahul.

[This message has been edited by rahul_mkar (edited June 21, 2000).]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic