How to get around the lack of abstract fields in Java?

Suppose we have an abstract class A, and we want to force all subclasses to have a specific field. This is not possible in Java because we cannot define abstract fields.

Workaround 1: Force subclasses to implement a method that provides the desired value.

abstract class A {
  abstract int getA();
}

Disadvantage: each subclass must implement a method for each abstract field that we want to have. This can lead to many method implementations.

Advantage: we can use the method getAin an abstract class and implement methods with it in Awithout their implementation in each subclass. But the value of the method cannot be overwritten by an abstract class.

Workaround 2: Simulate an abstract field, forcing a subclass to give the abstract class a value.

abstract class A {
  int a;

  public A(int a) {
    this.a = a;
  }
}

Disadvantage: when we have several fields (> 10), calling the super constructor will look a little ugly and confusing.

Advantage: we can use the field Ain an abstract class and implement methods with it in Awithout implementing them in each subclass. In addition, the value Acan be overwritten by an abstract class.

Question: What workaround is a common way to achieve a goal? Maybe better than higher?

+5
source share
5 answers

The abstract method is probably the most object oriented.

, POJO ( ).

+2

. fileds, . /

. . java -

+1

, opt.1 - . , , , "".

opt.2 , , , , a.

0

2 - :

1) , , - - , , "" ,

2) , , , . , , , , , .

note: , 10 , , -, , .

0

1. , , ,       .

2. , , .

3. 1- , . 1- .

:

Painting paint().

paint() , , .., .

.

public interface Paint{

paintDoIt(String style);

}

4. Your 2nd Wordaround will be good in a place where you want certain behaviors to be MUST be implemented by a subclass.

For instance:

Consider the car as an abstract class , now to be carit is very important that it should have a steering, 4 wheels, engine, etc. Therefore, these functions must be implemented .

where other functions such as music system, LCD, etc. are optional and depend on the type of vehicle.

0
source

All Articles