자바 질문입니다.
조회수 1033회
public class HelloWorld extends A {
String b = "HelloWorld";
public static void main(String []args){
HelloWorld helloWorld = new HelloWorld();
helloWorld.bb();
}
}
class A {
public void bb(){
System.out.println(b);
}
}
class A
안에 println(b)
가 class HelloWorld
안에 있는 String b = "HelloWorld"
를 참조해서 출력하려면
어떻게 식을 수정하거나 작성해야하나요??
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
1 답변
-
public class HelloWorld extends A{ String b = "HelloWorld"; public static void main(String []args){ A Class = new A(); Class.bb(); } } class A { public void bb(){ HelloWorld helloWorld = new HelloWorld(); System.out.println(helloWorld.b); } }
static변수를 이용해서 하면 편하겠지만 객체생성과 참조로 출력을 하시려면, HelloWorld 객체 생성을 클래스 A에 해주시고 println으로 출력할 때 객체 생성한 참조변수인 helloWorld를 이용해서 변수를 불러오기 위해 helloWorld.b로 값을 넣어주시고요. 이후에 메인에서도 class A를 객체로 생성한 후 bb메소드를 호출하시면 출력이 되네요. 사실 이것과 같이 코딩할 경우에는 상속을 굳이 하지 않아도 되겠지요.
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력