简体   繁体   中英

How can I get subclass value from super class method in Java?

I have these two classes:

Class A 
{
  public int max = 100;

  public int getMax()
  {
     return max;
  }
}



Class B extends A
{
  public int max = 200;
}

I write the following code:

A clsA = new A();
B clsB = new B();


valA = clsA.getMax();
valB = clsB.getMax();

valA is 100 valB is 100 again

How can I write code that clsB.getMax(); returns 200?

You can override getMax in class B:

  @Override
  public int getMax()
  {
     return max;
  }

Though, in general, it's a bad idea to have variables with the same name in the super class and the sub-class.

Note that after the change, the following will also return 200 :

A clsB = new B();
valB = clsB.getMax();

Override the getMax method in B :

class B extends A
{
    public int max = 200;

    public int getMax()
    {
       return max;
    }
}

In the getter method, return max; is equivalent to return this.max where this references the current instance of B . On the other hand, calling return super.max returns the max field value referenced in the parent subclass.

the short answer is that you can't override members in subclasses like you are trying. What you instead should do is make B change the value of max directly. Something like this:

class B extends A
{
    public B() 
    {
        max = 200;
    }
}

You have to add method getMax() to class B . The implementation might be the same as in Class A

@Overwrite
public int getMax()
{
   return max;
}

When you DO NOT overwrite the method one from B calls parent's method getMax() . And parent metod getMax() returns 150

Try Method Overriding

In Java, the "closest method" will be called. Because clsB extends A, but doesn't have it's own definition of getMax(), A's version of getMax() will be called. However, because clsB also shares the variables of A, getMax (called from class A) will return class A's number.

The solution? add

public int getMax()
{
     return max;
}

to class B.

Implement Method override concept

 @Override
  public int getMax()
  {
     return max;
  }

Overriding happens at run time

A clsB = new B();
valB = clsB.getMax();

Hope this should work.

Java does not support override any variables in a class.

You can have two ways to do it.

  1. Pass the variable through a constructor . I suggest doing this way because, if the method do the same action. By overriding it and doing it again is a bad practice.

    Class A { public int max = 100; public A(int maxVal) { this.max=maxVal; } public int getMax(){ return max; } } B clsB = new B(); A clsA = new A(clsB.max);

  2. Override the method

    @override public int getMax(){ max=200; //do the job. }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM