2014-02-07 5 views
0

추상 생성자의 작동 방식을 이해하는 데 문제가 있습니다. 나는 추상적 인 수퍼 클래스가 등뼈와 같아야한다는 것을 알고 있으며, 모든 하위 클래스는 그 안에 메소드가 있어야하지만 생성자 측을 이해하지 못한다.Java 추상 생성자 문제

public abstract class Animal{ 
      public String name; 
      public int year_discovered; 
      public String population; 

public Animal(String name, int year_discovered, String population){ 
      this.name = name; 
      this.year_discovered = year_discovered; 
      this.population = population; } 
      } 

위 내 초록 클래스입니다. 아래는 내 하위 클래스입니다.

public class Monkey extends Animal{ 
      public String type; 
      public String color; 

public Monkey(String type, String color){ 
      super(name,year_discovered,population) 
      this.type = type; 
      this.color = color;} 
       } 

나는 supertype 생성자가 호출되기 전에 참조하려고한다는 오류 메시지가 나타납니다.

이제 내가이 작업을 수행하는 이유는 각기 다른 종마다 코드를 복제 할 필요가 없기 때문입니다. 이 코드는 내가 혼란에 빠지도록 도와주기 위해 만든 간단한 예일뿐입니다. 앞으로의 답장을 보내 주셔서 감사합니다.

+0

? . 당신은 생성되기 전에 (즉, 생성자가 호출되기 전에) 부모의 필드에 접근 할 수 없다. – TheLostMind

+3

'supertype 생성자를 호출하기 전에이를 참조하려고한다. '--- 당신은 슈퍼 타입 생성자가 완료되기 전에 슈퍼 타입 * 필드 *를 참조하십시오. –

+0

아, 필자는 다음과 같이 입력해야한다고 생각합니다. public String name; public int year_discovered; public String population; 실제 원숭이 클래스에서도 아무런 코드도 저장하지 않습니다. – Softey

답변

4

귀하의 Monkey 클래스 생성자는 다음과 같이한다 : 중복 코드도 컴파일 오류가없는이 없습니다

public Monkey(String name, int year_discovered, String population, String type, String color){ 
      super(name,year_discovered,population); 
      this.type = type; 
      this.color = color; 

이 방법.

+0

아하나. 나는 어딘가에 들판을 놓아야한다는 것을 내 머리 속에 알았지 만 지금은 이해가된다. 수퍼 클래스는 수퍼 클래스로 다시 참조하여 이미 수식 등을 할당합니다. 고맙습니다 – Softey

2

Monkey 클래스 생성자에서 초기화되기 전에 추상 클래스 변수 (name,year_discovered,population)에 액세스하고 있습니다. 아래처럼 사용하십시오.

public Monkey(String name, int year_discovered, String population, 
          String type, String color){ 
      super(name,year_discovered,population); 
      this.type = type; 
      this.color = color; 
2

귀하의 필드를 비공개로 공개하십시오.

1
이름 만약

하고 같은 원숭이 생성자를 정의 할 수 있습니다 각 하위 동물 정적 year_discovered 있습니다

하위 클래스 또는 생성자의 이름, year_discovered, 인구 필드는
public Monkey(String type, String color){ 
     super("Monkey",1900,"100000"); 
     this.type = type; 
     this.color = color; 
}