![](/img/trans.png)
[英]Two java files. Getting IllegalAccessError when running class with main method trying to access a method from the other file
[英]I am receiving an IllegalAccessError when trying to run the class with the main() method in it
我目前正在學習 java 並在嘗試運行書中的一個示例時遇到了這個錯誤。 Movie class 的編譯沒有錯誤,但是當嘗試運行或編譯 MovieTestDrive class 時,會發生這種情況:
Exception in thread "main" java.lang.IllegalAccessError: class MovieTestDrive tried to access field Movie.title (MovieTestDrive is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @1e4a7dd4; Movie is in unnamed module MovieTestDrive.main(MovieTestDrive.java:5) 上的加載程序“應用程序”)
這是兩個文件的源代碼:
public class Movie {
String title;
String genre;
int rating;
void playIt() {
System.out.println("Playing the Movie");
}
}
public class MovieTestDrive extends Movie {
public static void main(String[] args) {
Movie one = new Movie();
one.title = "Gone with the Stock";
one.genre = "Drama";
one.rating = -2;
Movie two = new Movie();
two.title = "Avengers";
two.genre = "Action";
two.rating = 8;
two.playIt();
}
}
如果有人知道為什么會發生這種情況,我將非常感謝您在修復方面的幫助,更重要的是了解為什么會首先出現此問題。
嘗試公開playIt()
方法和public
字段變量,以便可以訪問它們:
class Movie {
public String title;
public String genre;
public int rating;
public void playIt() {
System.out.println("Playing the Movie");
}
}
class MovieTestDrive {
public static void main(String[] args) {
Movie one = new Movie();
one.title = "Gone with the Stock";
one.genre = "Drama";
one.rating = -2;
Movie two = new Movie();
two.title = "Avengers";
two.genre = "Action";
two.rating = 8;
two.playIt();
}
}
公共方法/字段將對使用Movie
class 的類可見。 如果不指定方法的訪問修飾符,默認情況下它會獲得包私有訪問 - 即只有同一 package 中的類可以訪問方法/字段。
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
作為委托人,授予字段/方法正常工作所需的最少權限。 因此,我們希望盡可能限制訪問,作為主體... private
是 class 字段的典型值,而private
/ public
/ protected
則用於 class 方法。
嘗試從 MovieTestDrive class 中刪除extends Movie
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.