Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java abstract class and overriding variables

I have encountered a problem which I cannot solve. Let's say we have the superclass A:

public enum Enumeration {
  A, B, C;
}

public abstract Class A {
     private Enumeration e;

     public void someMethod {
           // do something here with 'e'.
     }
}

Now let's assume we have an class B.

public Class B extends A {
    private final Enumeration = e.A;
}

Here I get a compiler warning that the value is never used.

I just want to define the method in Class A, thus I have to define the variable. But I want to give the variable a new fixed value in the subclass.

Is this not possible?

like image 360
machinery Avatar asked Jan 31 '26 15:01

machinery


1 Answers

Field can't be overridden. If you want to assign a specific enum instance to the class, use the constructor:

public abstract Class A {
     private final Enumeration e;

     protected A (Enumeration e) {
         this.e = e;
     }

     public void someMethod {
           // do something with 'e'.
     }
}

public Class B extends A {
    public B() {
        super(Enumeration.A);
    }
}
like image 124
Bohemian Avatar answered Feb 03 '26 05:02

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!