Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Call subclass variables from superclass

 
John Lockheart
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
  •  
    Garrett Rowe
    Ranch Hand
    Posts: 1296
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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 ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic