gpt4 book ai didi

Java,导入未解析,继承,内部类

转载 作者:行者123 更新时间:2023-12-01 18:09:50 30 4
gpt4 key购买 nike

最近求java编程,遇到一个错误。请帮忙

有两个类,PersonTest.java:

 public class PersonTest {

public static void main(String[] args) {
Person person1=new Person("dummy","sdymmt","20","male","washington");
System.out.println("Name: "+person1.getName());
System.out.println("Surname: "+person1.getSurname());
System.out.println("Age: "+person1.getAge());
System.out.println("Gender:" +person1.getGender());
System.out.println("Birthplace: "+person1.getBirthplace());
Person person2= new Person(400);
System.out.println("Income:"+person2.getX()+" mije leke");
System.out.println("Tax:"+person2.Taksat()+" mije leke");
Student student1= new Student("adsd","zedsdsadza");
System.out.println("emri"+student1.getEmer());
}

}

还有 Person.java :

public class Person {
private String Name;
private String Surname;
private String Age;
private String Gender;
private String Birthplace;
private double x;
public Person()
{

}
public Person(String Name, String Surname, String Age, String Gender, String Birthplace) {
this.Name = Name;
this.Surname = Surname;
this.Age = Age;
this.Gender = Gender;
this.Birthplace = Birthplace;

}

public String getName() {
return Name;
}

public String getSurname() {
return Surname;
}

public String getAge() {
return Age;
}

public String getGender() {
return Gender;
}

public String getBirthplace() {
return Birthplace;
}

public Person(double x) {
this.x = x;
}

public double getX() {
return x;
}

double Taksat() {
return (0.1 * x);
}

public class Student extends Person {
private String University;
private String Faculty;

public Student(String Universiteti, String Fakulteti) {
super(Name, Surname, Age, Gender, Birthplace);
this.Faculty = Fakulteti;
this.University = Universiteti;
}

public String getFaculty() {
return Faculty;
}

public String getUniversity() {
return University;
}
}
}

两个类位于同一个默认包中。如何解决测试类无法将内部类学生识别为类的问题。

最佳答案

嵌套的非静态类称为内部类,这些类如果没有外部类(包装它们)就无法存在。

Java docs

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

尝试使用:

Person.Student student = person1.new Student(PARAMETERS);

重要标记:

当然,您应该高度考虑这不是一个好的设计,因为您可能希望此类在 Person 类 之外可见,而且还因为 Person.Student 继承自 Person,它已经包含 Student 类,它通常看起来像一个循环或圆圈关系,这通常不是一个好主意。

关于Java,导入未解析,继承,内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861594/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com