假设抽象超类包含一个名为price类型为double的私有变量。使用重写抽象方法从超类访问私有变量
现在假设变量已被声明但未初始化。超类包含访问方法,但是setter方法是抽象的,因此它必须在子类中重写,但是,由于超级变量是私有的,有没有办法从子类初始化这个变量?
考虑下面的例子:我有4个类; Book(抽象超级),NonFiction(子),Fiction(子),Tester(类来测试会发生什么)。
Book类:
public abstract class Book {
private String title;
private double price;
Book(String name){
title = name;
}
public String getTitle(){
return title;
}
public double getPrice(){
return price;
}
public abstract void setPrice(double cost);
}
的小说类
public class Fiction extends Book{
Fiction(){
super("Harry-Potter");
setPrice(24.99);
}
@Override
public void setPrice(double cost) {
}
}
非小说类类
公共类非小说类作品延伸预订{
NonFiction(){
super("Head-first Java");
setPrice(37.99);
}
public void setPrice(double cost) {
}
}
测试机柯乐小号
public class Challenge {
public static void main(String[] args){
Fiction fictionBook = new Fiction();
NonFiction NonFictionBook = new NonFiction();
Book[] theList = new Book[2];
theList[1] = NonFictionBook;
theList[0] = fictionBook;
System.out.println("Title of fiction book: \n"+theList[0].getTitle());
System.out.println("Title of non fiction book \n"+theList[1].getTitle());
System.out.println("Title - "+theList[0].getTitle()+" -" + theList[0].getPrice());
System.out.println("Title - "+theList[1].getTitle()+" -" + theList[1].getPrice());
}
}
预期的输出应该是:
小说书名: 哈利波特 标题非小说类文学作品的: 头第一个Java 标题,哈利·波特的成本 - $ 24.99 标题,头 - 第一个Java成本 - $ 37.99
有没有办法访问私有变量而不需要将范围更改为受保护的?
哦,是的,就像字符串如何默认初始化为null。 另外,如果其中一个访问器方法是抽象的,并且封装变量是私有的,那么访问器基本不工作? – RamanSB
@Ramandeep:是的,任何引用类型都被初始化为null。 –
@Ramandeep:子类无法在超类中看到私有变量。 –