2016-12-22 6 views
0

나는 Dog, Cat 및 Rabbit과 같은 여러 하위 클래스가있는 추상 클래스 인 Animal을 사용합니다.객체에 상수 할당

각 하위 클래스는 Animal 클래스의 생성자를 사용하지만 하위 클래스의 모든 객체도 상수가 필요합니다. Dog 객체는 항상 animalNumber = 1이고 모든 Dog 객체는 maximumNumberOfAnimals = 5 특성을 가져야합니다. 그러나 모든 Cat 객체는 항상 animalNumber = 2이어야하고 모든 Cat 객체는 maximumNumberOfAnimals = 10 속성을 가져야합니다.

이 코드를 작성할 수 있습니까? 이것은이 다른 서브 클래스

public class Cat extends Animal { 

public static final int ANIMALNUMBER= 2; 
public static final int MAXIMUMNUMBERALLOWED= 10; 

//the constructor 
public Cat (int weight, int height, int animalNumber, int maximumNumberAllowed) { 
    super(weight, height) 
    Cat.animalNumber = ANIMALNUMBER; 
    Cat.maximumNumberAllowed = MAXIMUMNUMBERALLOWED; 
} 
} 

에게 있습니다

public class Dog extends Animal { 

public static final int ANIMALNUMBER= 1; 
public static final int MAXIMUMNUMBERALLOWED= 5; 

//the constructor 
public Dog (int weight, int height, int animalNumber, int maximumNumberAllowed) { 
    super(weight, height) 
    Dog.animalNumber = ANIMALNUMBER; 
    Dog.maximumNumberAllowed = MAXIMUMNUMBERALLOWED; 
} 
} 

서브 클래스에게 있습니다

public abstract class Animal { 
private int weight; 
private int height; 

public Animal (int weight, int height) { 
setWeight(weight); 
setHeight(height); 
} 

public int getWeight() { 
    return weight; 
} 
public void setWeight(int weight) { 
    this.weight = weight; 
} 

public int getHeight() { 
    return height; 
} 

public void setHeight(int height) { 
    this.height = height; 
} 
} 

:이 슈퍼 클래스입니다

:

내가 지금까지 무엇을 가지고 내가 뭐야? nt는 다음과 같습니다.

개 Lassie = new Dog (40, 60, 1, 5)를 사용하여 새 'Dog'를 만들기 위해 생성자를 호출하면됩니다. 그러나 나는 이것을 허용해서는 안됩니다 : Dog Lassie = new Dog (40, 60, 2, 10) 모든 Dog에 대해 ANIMALNUMBER는 1이어야합니다. 모든 Cat에 대해 ANIMALNUMBER는 2 여야합니다. 인스턴스 변수이지만 클래스의 모든 인스턴스에 대해 동일해야합니다.

이것은 말합니다 : 최종 필드 Dog.ANIMALNUMBER는 할당 할 수 없습니다. 그러나 나는 또한 그것이 작동하지 않을 것이라고 생각합니다. 제안 사항이 있으십니까?

미리 감사드립니다.

+0

생성자에서 그것들을 재 할당하는 동안 그것들은'final'과'static'을 사용합니다. 당신은 아마 어떤 것들을 섞어 버릴 것입니다. 당신은 아마 당신이이 변수들을 가지고하려고하는 것을 추가해야 할 것입니다. – SomeJavaGuy

+1

'빌라 '는 어디에서 왔습니까? 당신이 준 코드에있는 것이 아닙니다. 이 오류는 당신의 질문과 관련이없는 것처럼 보입니다. – RealSkeptic

+0

죄송합니다. 다른 클래스에서 동일한 오류가 발생했습니다. 실제로, 이것은이 질문과 관련이 없습니다. – Waterfles

답변

0

생성자에서 상수 값을 설정하려면 비 정적으로 설정해야합니다. 하지만 이제 전역 상수가 생겼으므로 animalNumber 및 maximumNumberAllowed를 생성자로 전달하는 것은 의미가 없습니다. 귀하의 상수는 항상 같은 설정 같은 값을 갖게됩니다

public static final int MAXIMUMNUMBERALLOWED = 10; 

그리고 개 클래스의 상수는 고양이 클래스의 상수 관련이없는!

1

그래서 모든 개를 들어, ANIMALNUMBER 모든 고양이를 들어, ANIMALNUMBER 2.

당신 overcomplicated 것들이어야한다, 1이어야한다. 가장 쉬운 해결책은 Constructor 매개 변수를 제거하고 ANIMALNUMBER을있는 그대로 유지하는 것입니다. 서브 클래스에 대한 ID를 정의

그러나

나중에 동물의 ANIMALNUMBER에 특별한 액션 기지를 할 계획을 의미한다.

이것은 우리가 OOP를 할 때 우리가 원하는 것이 아닙니다.

와트 혹시 나중에 할 원하는 (Dog을 같은) 클래스 Animal

public abstract class Animal { 
    // common fields 
    public Animal (int weight, int height) { 
    // initialize 
    } 

    public abstract sting giveSound(); 
} 

public class Dog extends Animal { 
    @Override 
    public sting giveSound(){ 
    return "Wooff"; 
} 


public class Cat extends Animal { 
    @Override 
    public sting giveSound(){ 
    return "Meaw"; 
} 

public class Rabbit extends Animal { 
    @Override 
    public sting giveSound(){ 
    return ""; 
} 

를 [에 추상 메소드를 오버라이드 (override) ANIMALNUMBER 콘크리트의 방법으로 수행해야합니다에 따라 "동물"구현을 편집]

나는이 동물들을 어떤 시점에서 그리드에 배치 할 것이다. 그리고 나는 가지고있는 개, 고양이 및 토끼의 수를 세고 싶습니다. 나는이 코너 케이스의 일종임을 인정해야

...

는 내가 자신의 클래스에 기반을 셀 수 있습니까?

예, 사용하여 Map :

public abstract class Animal { 
    public addToCount(Map<String,Integer> counters){ 
    // gets the class name of the child that has been called *new* on... 
    String myClassName = getClass().getName(); 
    Integer oldCount = conters.getOrDefault(myClassName, Integer.ZERO); 
    conters.put(myClassName,oldCount.add(Integer.ONE)); 
    } 
} 
+0

나는이 동물들을 어떤 시점에서 그리드에 놓을 것이다. 그리고 나는 가지고있는 개, 고양이 및 토끼의 수를 세고 싶습니다. 수업을 기준으로 계산할 수 있습니까? – Waterfles

+0

@Waterfles * "수업을 기준으로 계산할 수 있습니까?"* 내 편집을 참조하십시오. –

1

당신은 Animal이 두 속성을 추가하고 아이 클래스에서 그들을 초기화 할 수 있습니다 : 그것은 나던하게 이해

public abstract class Animal { 
    private int weight; 
    private int height; 
    private final int number; 
    private final int maximumAllowed; 

    public Animal(int weight, int height, int number, int maximumAllowed) { 
     setWeight(weight); 
     setHeight(height); 
     this.number = number; 
     this.maximumAllowed = maximumAllowed; 
    } 

    public int getWeight() { 
     return weight; 
    } 

    public void setWeight(int weight) { 
     this.weight = weight; 
    } 

    public int getHeight() { 
     return height; 
    } 

    public void setHeight(int height) { 
     this.height = height; 
    } 

    public final int getNumber() { 
     return number; 
    } 

    public final int getMaximumAllowed() { 
     return maximumAllowed; 
    } 
} 

public final class Dog extends Animal { 
    public Dog(int weight, int height) { 
     super(weight, height, 1, 5); 
    } 
} 

public final class Cat extends Animal { 
    public Cat(int weight, int height) { 
     super(weight, height, 2, 10); 
    } 
}