您不能直接从Driver 类访问private 或protected 变量,如isbn 或title。它根本不会编译。访问超出其预期隐私范围的变量或方法将无法编译。因此,那里涵盖了您正在寻找的隐私测试,并作为访问修饰符有效的证据。
如果您确实希望能够从预期隐私之外访问private 和protected 变量,那么您将使用下面提到的设计模式:
有很多方法(您可以使用设计模式)来解决这个问题。传统的方法是向类添加 getter 和 setter 以访问其属性。
PaperPublication 类:
package paperPublication;
public class PaperPublication {
protected String title;
protected double price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
书籍类:
package book;
import paperPublication.PaperPublication;
public class Book extends PaperPublication {
protected long isbn;
protected int issueYear;
public long getIsbn() {
return isbn;
}
public void setIsbn(long isbn) {
this.isbn = isbn;
}
public int getIssueYear() {
return issueYear;
}
public void setIssueYear(int issueYear) {
this.issueYear = issueYear;
}
}
驱动类:
package driver;
import book.*;
import paperPublication.PaperPublication;
public class Driver {
public static void main(String[] args) {
Book a = new Book();
a.setIsbn(123456789L);
a.setTitle("Best book ever!");
System.out.println(a.getIsbn());
System.out.println(a.getTitle());
}
}
另一种设计模式是只有 getter,并且在创建对象时设置一次值:
PaperPublication 类:
package paperPublication;
public class PaperPublication {
protected String title;
protected double price;
public PaperPublication(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
}
书籍类:
package book;
import paperPublication.PaperPublication;
public class Book extends PaperPublication {
protected long isbn;
protected int issueYear;
public Book(long isbn, int issueYear, String title, double price) {
this.super(title, price);
this.isbn = isbn;
this.issueYear = issueYear;
}
public long getIsbn() {
return isbn;
}
public int getIssueYear() {
return issueYear;
}
}
驱动类:
package driver;
import book.*;
import paperPublication.PaperPublication;
public class Driver {
public static void main(String[] args) {
// things are set in the constructor, and then you can only read, not change the values.
Book a = new Book(123456789L, 2018, "Best book ever!", 19.99);
System.out.println(a.getIsbn());
System.out.println(a.getTitle());
}
}
还有更多方法,这完全取决于您的需求。