File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Call subclass variables from superclass Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Call subclass variables from superclass" Watch "Call subclass variables from superclass" New topic

Call subclass variables from superclass

John Lockheart
Ranch Hand

Joined: Oct 13, 2006
Posts: 115
I understand how to call superclass variables from a subclass. But what if I wanted to call subclass variables from the superclass. Or even sub subclass variables (a subclass inside a subclass of the superclass) from a superclass. I want to reach down the Hierarchy for variables as opposed to reaching up (like when using super). How do I do that? Or is it not possible because the super class can't inherit any of the subclass variables? I'll use examples from the program i've been working on. I know there's supposed to be more code but I just slapped that together.

mohsen fakhari

Joined: May 04, 2003
Posts: 25
When you modify a variable of Threat from Virus,in fact you modify a variable of Virus itself,because Virus instances do have all variables of Threat.
But speaking about a Threat instance,Virus is completely stranger whom it knows nothing about.
marc weber

Joined: Aug 31, 2004
Posts: 11343

On the surface, that's a reasonable question. But consider these issues:
  • How would a superclass "know" what subclasses are extending it?
  • If it did know, how might a superclass decide which of these subclasses to try to get a value from?
  • More fundamentally, what could a superclass do with a value from a subclass? In other words, why would the state of a subclass be of any concern to a superclass?

  • "We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
    Garrett Rowe
    Ranch Hand

    Joined: Jan 17, 2006
    Posts: 1296
    If these behaviors should be common to all sub classes, then you can move the behaviors there:

    This forces the subclasses to implement behavior that can be used by the superclass. Polymorphism.
    [ January 27, 2007: Message edited by: Garrett Rowe ]

    Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
    I agree. Here's the link:
    subject: Call subclass variables from superclass