2017-01-23 1 views
0

자바에서 객체를 참조하는 방법에 대해 더 잘 이해하고 싶습니다. 오류 올릴 것이다이 코드를 감안할 때 "오류 :이 정적 문맥에서 참조 할 수 없습니다 비 정적 변수"정적 컨텍스트에서 비 정적 변수 참조

public class Catalog { 
    public class Student { 
     public String name;   
     ... 
     } 
//Student 

    public static void main (String[] args){ 
     Student s; 
     s = new Student(); 
    }//main 

Q1 : 왜 작동합니까 수준의 학생이 다른 파일에 정의되어있는 경우 "Student.java "? 내가 메인 서브 루틴과 동일한 파일에 학생 클래스 정의를 유지하려면

, 해결이 게시물에 발견 "Non-static variable cannot be referenced from a static context는":

public class Catalog { 
public class Student { 
    public String name;   
    ... 
    } 

    public static void main (String[] args){ 
     oopExample prg;   
     prg = new oopExample(); 
     prg.run();  
    }//main 

    Student std1; 
    public void run(){ 

     std1 = new Student(); 
     std1.name = "Tobby"; 
    } 
}//oopExample 

Q2 :이가 비슷한 경우에 당신이 말해 줄 수 별도의 파일에서 Student 클래스 정의를 사용할 때의 프로그램 실행 시점

질문 3 : 학생을 정적이라고 선언 할 때의 단점은 무엇입니까? 단순히 다음 코드를 사용

public class Catalog { 
    public static class Student { 
     public String name;   
     ... 
     }//Student 

    public static void main (String[] args){ 
     Student s; 
     s = new Student(); 
}//main 

이 시간 내 주셔서 감사합니다

+1

기다려! 첫 번째 코드 스 니펫이 작동하지 않습니까? – CKing

+2

예, @CKing, 여기 '학생'은 정적이지 않은 내부 클래스 인'Catalog'이므로 인스턴스화되기 전에'Catalog' 인스턴스가 필요합니다. 정적 인'main' 메소드에는 그런 인스턴스가 없습니다. –

+0

정확히 내 지점. 당신은 그 해답을 알고 있습니까? 왜 아직도 묻고 있습니까 * Q1 : 클래스 Student가 다른 파일 "Student.java"에 정의되어있는 경우 왜 작동합니까? * – CKing

답변

0

Q1: Why does it work if class Student is defined in another file “Student.java”?

을 별도의 파일에 (만) 클래스는 암시 static 때문이다. 그것은 중요하지 않습니다보기의 프로그램 실행 관점에서

Q2: Can you tell me if this is similar from the program execution point of view with case when I use the Student class definition in a separate file?

(만큼 당신이 당신이 좋은 이유가 없다면 당신은, 어쨌든하지 말아야 클래스 Student (에서 클래스 Catalog 뭔가에 액세스하지 않는 한 .. .) 클래스 Student

Q3: What would be the drawbacks of declaring Student as static? and simply use the following code:

객체를 선언하지 않은 클래스 Catalog의 속성에 액세스 할 수 없습니다 static

그러나 다시를 :.이 뭔가있다 어쨌든 당신은 신경 써야합니다.

관련 문제