2016-12-14 1 views
1

자바에서 생성자가 호출 될 때마다 객체가 생성됩니까? 여기서 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 
+1

[Java에서 상속 - 가능한 하위 클래스의 개체를 생성하는 것은 수퍼 클래스의 생성자를 호출합니다. 왜 정확히?] (http://stackoverflow.com/questions/488727/inheritance-in-java-creating-an-object-of-the-subclass-invokes-also-the-constr) – DVarga

답변

1

생성자 호출은 새로운 객체를 생성하지 않습니다를 참조 것을 증명하기 위해서는 새로 생성 된 개체를 초기화합니다.

new Apple()으로 Apple 개체를 만들면 단일 개체가 만들어집니다. 객체의 속성을 초기화하려면 여러 생성자 (Apple, FruitObject)를 실행해야합니다.

0

개체의 생성자는 개체를 만드는 데 필요한 세부 정보를 지정하는 데 사용됩니다.

새로운 Apple()을 사용한 순간 객체가 생성되고 생성자의 코드가 초기화됩니다.

관련 문제