명확하게 인용된 구조에서 속성 실례와 관련된 문제

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에 처음 불러올 때 초기화되고 한 번만 초기화됩니다.그래서 구조 파라미터에서 전달은 합리적이고 컴파일러가 순조롭게 통과합니다!

좋은 웹페이지 즐겨찾기