자바에서 생성자가 호출 될 때마다 객체가 생성됩니까? 여기서 Apple 클래스는 Fruit.Apple 객체를 상속받습니다. Fruits를 상속하면 Fruit의 생성자가 호출됩니다 (생성자 연결). Fruit의 객체가 초기화되었습니다.자바에서 생성자가 호출 될 때마다 객체가 생성됩니까?
그러나 출력 결과는 하나의 객체 만 생성된다는 것을 나타냅니다. Apple 객체입니다. 모두 동일한 해시 코드를가집니다.
누군가 설명해 주시겠습니까? .2 개의 객체가있을 것으로 예상됩니다. 첫 번째 과일 객체가 초기화 된 다음 사과 객체가 초기화되어야합니다.
// 자바 프로그램이 모두 상위 클래스 //와 서브 클래스 생성자가 동일한 개체
// super class
class Fruit
{
public Fruit()
{
System.out.println("Super class constructor");
System.out.println("Super class object hashcode :" +
this.hashCode());
System.out.println(this.getClass().getName());
}
}
// sub class
class Apple extends Fruit
{
public Apple()
{
System.out.println("Subclass constructor invoked");
System.out.println("Sub class object hashcode :" +
this.hashCode());
System.out.println(this.hashCode() + " " +
super.hashCode());
System.out.println(this.getClass().getName() + " " +
super.getClass().getName());
}
}
// driver class
public class Test
{
public static void main(String[] args)
{
Apple myApple = new Apple();
}
}
Output
Super class constructor
Super class object hashcode :366712642
Apple
Subclass constructor invoked
Sub class object hashcode :366712642
366712642 366712642
Apple Apple
[Java에서 상속 - 가능한 하위 클래스의 개체를 생성하는 것은 수퍼 클래스의 생성자를 호출합니다. 왜 정확히?] (http://stackoverflow.com/questions/488727/inheritance-in-java-creating-an-object-of-the-subclass-invokes-also-the-constr) – DVarga