我正在尝试学习抽象方法和抽象类,但我不明白为什么会出错。谁能帮我找到错误原因吗?
我试图检查java文件以及类和方法的拼写。但是它们看起来还不错。
// Code from filename: Person.java
// abstract class
abstract class Person {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
// Subclass (inherit from Person)
class Student extends Person {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
}
}
// End code from filename: Person.java
// Code from filename: MyClass.java
class MyClass {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Person)
Student myObj = new Student();
System.out.println("Name: " + myObj.fname);
System.out.println("Age: " + myObj.age);
System.out.println("Graduation Year: " + myObj.graduationYear);
myObj.study(); // call abstract method
}
}
我遇到以下错误:
MyClass.java:4:错误:找不到符号 学生myObj =新的Student(); ^ ^符号:班级学生所在地:班级MyClass
答案 0 :(得分:-1)
您所有的类都具有无修饰符访问级别,这意味着它们仅对包可见。将MyClass
与Person
/ Student
放在同一包中,或将其更改为public class...
。
有关详细说明,请参见此:https://www.tutorialspoint.com/java/java_modifier_types.htm