![](/img/trans.png)
[英]How to manage a subclass of an abstract class via a third class(not extending the abstract class) if the subclass doesn't have a constructor?
[英]Subclass of abstract class can't see constructor
花了一些时间把我的头发拉出来。 看似黑白,但我似乎无法让它工作。 在我的类中对java中的抽象类所做的事情进行了大量挖掘,但无济于事。
我正在尝试做什么:作为一项任务的一部分(所以没有大的提示,除非它是我的IDE或其他东西),我正在制作一个客户类摘要,然后继续并从中制作一些子类。 通过这种方式,抽象类将通过创建利用抽象类方法/属性的子类来实例化。 和我一起到目前为止?
package customer;
abstract class Customer {
private String id;
private String name;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
//accessors
public double getDiscount(double amt) {
double discount = 0;
return discount;
}
public String getID() {
return this.id;
}
public String name() {
return this.name;
}
}
摘要客户类,似乎都很好,简单,容易。 现在是实体子类RetailCustomer
package customer;
public class RetailCustomer extends Customer {
private double rateOfDiscount = 0.04;
public RetailCustomer(String id, String name, double rate) {
super(id, name);
this.rateOfDiscount = rate;
}
//mutators
public void setDiscount(double rate) {
this.rateOfDiscount = rate;
}
//accessors
public double getDiscount() {
return this.rateOfDiscount;
}
}
好。 再次,非常简单。 RetailCustomer扩展了Customer抽象类,并且应该使用抽象类构造函数,如下所示
public RetailCustomer(String id, String name, double rate) {
super(id, name);
this.rateOfDiscount = rate;
}
但是我的IDE(Eclipse)显示错误“构造函数Customer(String,String)未定义”。 即使它在抽象类中明显存在。
注意:只需从https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html复制语法
另外作为一个补充问题(我最有可能通过实验来解决):
抽象Customer类实现了一些只是简单访问器的方法。我的理解是,除非这些方法由retialCustomer以某种方式实例化,否则对象不会实例化,因为所有方法都需要实现?
提前感谢您提供的任何提示或指示。 就像我说的,对我来说似乎很简单,但与此同时,获得zilch :(
你的代码看起来很好。 重建它(你可能也想看看IntelliJ IDEA;))。 另请遵循惯例并将您的课程重命名为RetailCustomer
。
抽象Customer类实现了一些只是简单访问器的方法。我的理解是,除非这些方法由retialCustomer以某种方式实例化,否则对象不会实例化,因为所有方法都需要实现?
你可能需要改写这个,因为它不清楚你的要求。 所有子类都将继承父类的实现。 即使您的父类是抽象的,如果您在类中实现了某些方法,那么所有子类都将继承这些实现。 实际上,您仍然无法实例化您的抽象类,但您可以使用子类中的这些方法。
如果您对Customer
的方法感到满意,则无需在RetailCustomer
覆盖它们。
我正在尝试做什么:作为一项任务的一部分(所以请不要大的提示,除非它是我的IDE或其他东西)
+1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.