File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem in Upcasting" Watch "Problem in Upcasting" New topic

Problem in Upcasting

Anshul Mathur

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.

class first
public void show()
System.out.println("Base Class");

static void tune(first f1)

public class Poly extends first

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

public static void main(String agrs[])
Poly p = new Poly();


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.


Anshul Mathur
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


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]
I agree. Here's the link:
subject: Problem in Upcasting
It's not a secret anymore!