1

Apologies if this has been posted before, I keep only getting results for overriding the opposite way.

I want to be able to do 2 things:

  1. Reference the parent variable from the child class, in assigning the value for the child variable.
  2. Have the method in the adult class that references this variable use the child classes value. That way, I can have a lot of child classes, but not have the same repeating code for the method.

Here's a super simple pseudo-example of what I mean:

child class:

public class ChildClass extends AdultClass {
    static int a=super.a+1;
}

adult class:

public class AdultClass {
    static int a=5;
    static public int getA() {
        return a;
    }
}

class that uses ChildClass object:

public class ClientClass {
    public static void main(String[] args) {
        ChildClass.a <-I want this to =6
        ChildClass.getA() <-I want this to return 6
    }
}
Perception
  • 79,279
  • 19
  • 185
  • 195
Vahag Byurat
  • 13
  • 1
  • 3

2 Answers2

2

If you want to leverage Java's polymorphism, you'll have to involve class instances. Static members cannot display polymorphic behavior, which you apparently require from AdultClass.getA().

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • I'm starting to see that I can't do what I'm trying to do. My main goal was to avoid repeating code, so I just left the parts of the method that are shared in the parent class, and had an additional method in each child will take care of the rest. – Vahag Byurat Feb 21 '13 at 00:09
0

then simply make the member a protected one, and use it as the child's own member.

this link may be useful too. why instance variable of super class is not overridden in sub class method

Community
  • 1
  • 1
Ariel Pinchover
  • 654
  • 3
  • 17