Java 抽象类的静态成员

问题描述 投票:0回答:2

我有以下设置:具有属性

Vehicle
的超类
capacity
和两个子类
Bus
Tram
。所有有轨电车和所有公共汽车都具有相同的容量(应该是静态属性),但有轨电车的容量可能与公共汽车的容量不同。如何在Java中实现这样的方法?

我已经部分解决了这个问题,只是忽略了容量应该是所有子类的静态属性(没有静态属性)这一事实。

java oop static abstract-class superclass
2个回答
0
投票

使

capacity
只能通过
Vehicle
构造函数分配,并让继承者提供其预定义值 - 通过其构造函数公开它。

public abstract class Vehicle {

  private final int capacity;

  protected Vehicle(int capacity) {
    this.capacity = capacity;
  }

  //maybe a getter for capacity?
  //or use it in other methods as needed
}

对于此示例,特别是继承构造函数是无参数的,但如果需要,它可以设置

Bus
的特定属性,以及
capacity
中的其他属性。

public class Bus extends Vehicle {

  //every bus has the same capacity - 50
  private static final int BUS_CAPACITY = 50;

  public Bus() {
    super(BUS_CAPACITY);
  }
  
  //other bus specific stuff
}

0
投票

您应该将容量封装在

getCapacity
方法中。然后,该方法可以为特定类查找适当的静态变量,例如:

abstract class Vehicle {
    public int getCapacity();
}

class Tram {

    private static final int TRAM_CAPACITY = 200;

    @Override
    public int getCapacity() {
        return TRAM_CAPACITY;
    }
}

class Bus {

    private static final int BUS_CAPACITY = 100;

    @Override
    public int getCapacity() {
        return BUS_CAPACITY;
    }
}

这还有一个额外的好处,如果有一天你想根据其他一些属性来计算容量(例如,给定单个推车容量的电车上的座位数乘以推车数量),你可以直接修改

getCapacity
无需修改客户端代码。

class Tram {

    private static final int CART_CAPACITY = 100;

    private int carts;

    public Tram(int carts) { this.carts = carts; }

    @Override
    public int getCapacity() {
        return CART_CAPACITY * carts;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.