명확하게 인용된 구조에서 속성 실례와 관련된 문제
2448 단어 jvm
class Person{
String name;
String location;
Person(String name,String location){
this.name = name;
this.location = location;
}
Person(String name){
this.name = name;
location = "dongguan";
}
void info(String name,String location){
System.out.println("My name is "+name+" and I'm comr from "+location+".");
}
}
class Student extends Person{
private String school;
Student(String name,String location){
this(name,"beijing",school);
}
Student(String n,String l,String school){
super(n,l);
this.school = school;
}
}
언뜻 보기에는 괜찮은데?다시 보니 문제가 생겼다
//Student Person
Student(String name,String location){
// Super(String name,String location)
// Person(String name,String location)
// name location
// Student(String n,String l,String school)
this(name,"beijing",school);// school
}
Student(String n,String l,String school){
super(n,l);
this.school = school;
}
문제는 바로 이 스쿨에게서 나온다.삼삼 구조에서 하나의Stringschool을 전달하여 속성school을 부여하지만 양삼의 구조에서 삼삼 구조를 호출하면 그에 상응하는 String 유형이 school에게 전달되지 않는다. 여기서 전달하는school은 바로 속성school 자체이다.
구조는 속성을 초기화하는 데 쓰인다.school 성명 시 기본적으로null을 초기화합니다. 여기에서 자신을 초기화합니다.이렇게 하면 사실 변형이 static의 효과를 실현하고 모든 대상에게 같은 속성 school을 가지게 하지만 school은 static이 아니기 때문에 컴파일러를 통과시킬 수 없을 것이다.
해결 방법: school을 정적 속성으로 바꾸기
class Student extends Person{
private String static school;
Student(String name,String location){
this(name,"beijing",school);
}
Student(String n,String l,String school){
super(n,l);
Student.school = school;
}
}
static 속성은 클래스와 관련이 있기 때문에 클래스가 jvm에 처음 불러올 때 초기화되고 한 번만 초기화됩니다.그래서 구조 파라미터에서 전달은 합리적이고 컴파일러가 순조롭게 통과합니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
간단하게 말하자면, Scala 집합하위 패키지의 모든 정의를 포함합니다.당신이 처리할 대부분의 추상은 여기에 정의되어 있습니다.collection.concurrent매핑 피쳐와 TrieMap 클래스를 정의하려면 원자적이고 잠금 없는 액세스 작업을 사...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.