This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Problem in Upcasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem in Upcasting" Watch "Problem in Upcasting" New topic
Author

Problem in Upcasting

Anshul Mathur
Greenhorn

Joined: Nov 07, 2003
Posts: 22
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
 
subject: Problem in Upcasting
 
Similar Threads
Assigning subclass obj to superclass ref
Mock Exam question.
Problem on Polymorphism
shadowing
What is ArrayStoreException and when it happens