File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in Upcasting

 
Anshul Mathur
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello all


I am having a problem with UPCASTING in the following code. this is the code i am trying to run.


<CODE>
class first
{
public void show()
{
System.out.println("Base Class");
}

static void tune(first f1)
{
f1.show();
}
}

public class Poly extends first
{

public void display()
{
System.out.println("Display");
}
public void show()
{
System.out.println("Derived Class");
}

public static void main(String agrs[])
{
Poly p = new Poly();
first.tune(p);
}
}

</CODE>

my Expected out put should be "Base Class" but the out put is "Derived Class" . Am i Missing something . If yes how can i access <B> show()</B> of <B> first </B> other than simply making an object of first and accessing it.

Thanks


Anshul Mathur
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Yes, you're missing something. Any time you call a method of any object, the most-derived version of that method is invoked. The compile-time type of a variable referring to the object has no effect at all; only the runtime type of the object matters.

A subclass can invoke a superclass's version of a method using the "super.method()" syntax, but there's no way for any other class to invoke a superclass method from a subclass object. It's against the rules in Java, and there's no way around it.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic