이 개체 (제목에 명시된)는 자식 클래스의 재정의 된 메서드를 호출 할 수 있으므로 다른 자식 메서드 메서드를 호출 할 수없는 이유는 무엇입니까? 메모리 구조, JVM 등의 내부 논리와 같은 가능한 자세한 답변이 필요합니다.자식 클래스 개체에 대한 참조를 가진 부모 클래스 형식 참조 변수가 자식 클래스의 메서드에 액세스 할 수없는 이유
아래 코드는 내 질문에 대한 명확한 이해를 제공합니다.
class A
{
int x=10;
public A()
{
System.out.println("Constructor of class A called!!!");
}
public void sayGreetings()
{
System.out.println("accept hye from class A");
}
}
class C extends A
{
int x=30;//why this is not accessed by stated object.
public C()
{
System.out.println("Constructor of Class C caled!!!");
}
public void sayGreetings()
{
System.out.println("accept hye from class C");
}
public void ssa()
{
System.out.println("Sat Sri Akal ji from class C");
}
}
public class ParentClassTypeObject
{
public static void main(String[] args)
{
C cObj=new C();
cObj.sayGreetings();
cObj.ssa();
A aCObj=new C();//this is let say stated object,main object
aCObj.sayGreetings();/*here we invoked method will be child class's
overriden method.*/
//aCObj.ssa(); //why this line gives error
System.out.println("x="+aCObj.x);
}
}
하지만 내 질문에 왜 오버라이드 된 메서드에 액세스 할 수 있지만 다른 자식 메서드는 액세스 할 수없는 대답을주지 않았다. ineed 대답. 컴파일러가 우리가 aCObj.sayGreetings()를 호출 할 때 자식 클래스에서 재정의 된 메서드를 선택하는 방법. 클래스 A의 메서드 (sayGreetings()가 호출되지 않았습니다.) –