我有一个父类,其中我有一个最终的静态int,我需要在子类中隐藏它。在父类中,我使用方法“print”,我在我的子类中重写。如果我使用此代码,方法print将使用我父类的MINIMUMPRIJS。如何使用我的子类中的MINIMUMPRIJS?
在我的任务描述中,它说的是关于“reis”的类:
- 确保价格至少为5欧元。为此创建一个变量,并确保始终保证这个最小化
- 1个构造函数,带1个参数(目标)
- 1个带参数的构造函数(destiantion,price)
关于班级“vliegtuigreis”
- 在这里,最低限额是25欧元。做需要的事。
- 1个只有1个参数(目标)的构造函数
- 1个带参数的构造函数(目的地,价格和航班号)
public abstract class Reis {
public final static int MINIMUMPRIJS = 5;
public void setPrijs(double prijs) {
if (prijs >= getMINIMUMPRIJS()) {
this.prijs = prijs;
}else{
this.prijs = MINIMUMPRIJS;
}
}
public void print(){
System.out.printf("Reis met bestemming %s kost %,.2f euro. %n", bestemming, prijs);
}
}
public class VliegtuigReis extends Reis {
private final static int MINIMUMPRIJS = 25;
public void print(){
super.print();
System.out.println("Vluchtnr " + vluchtnummer);
}
}
答案 0 :(得分:0)
您可以为默认值定义常量,但随后使用字段存储动态值。你根本不需要“隐藏”父母的最低价格,你只需要在孩子身上引用一个不同的常数。
public abstract class Parent {
public static final double MIN_PRICE = 5.0;
private double price;
public Parent() {
this(MIN_PRICE);
}
public Parent(double price) {
this.price = Math.max(price, Parent.MIN_PRICE);
}
public print() {
System.out.println("Price is: " + this.price);
}
}
public class Child extends Parent {
private static final double MIN_PRICE = 25.0;
public Child() {
super(Child.MIN_PRICE);
}
public Child(double price) {
super(Math.max(price, Child.MIN_PRICE));
}
public void print() {
super.print();
System.out.println("Other stuff");
}
}
希望您可以将其扩展到其他要求。