나는 문구가 약간 혼란스럽고 이상하다는 것을 알고있다. 그러나 나와 맺어 라. 다음라는 클래스 ChildBlah
(그래서 SuperBlah-Blah-ChildBlah
)에 Blah
을 상속 Java에서 부모 클래스의 자식 클래스 생성자를 통해 부모 클래스의 수퍼 클래스 생성자를 호출 할 수 있습니까?
SuperBlah
라는 클래스를 가지고 말해, 당신은
Blah
라는 클래스를 상속.
Blah
에 생성자가없는 경우
ChildBlah
의 생성자에 사용 된
super();
키워드가
SuperBlah
의 생성자라고합니다.
안된다고 대답 한 사람들에게 왜 이것이 효과가 있습니까? Critter 클래스를 확장하는 BlusterBug라는 클래스가 있으며 BlusterBug의 생성자에서 super를 호출합니다. Critter에는 생성자가 없지만 Critter가 확장하는 Class에는 생성자가 있습니다. (의도적으로 클래스의 나머지 코드는 생략했습니다.)
public class BlusterCritter extends Critter {
// instance vaiables
private int courageFactor;
private static final double DARKENING_FACTOR = 0.05;
// create a constructor(include what is necesary for parent)
public BlusterCritter(int c)
{
super();
courageFactor = c;
}
그런 다음 Critter 클래스에는 생성자가 없습니다!
public class Critter extends Actor// omitted all the code
{
/**
* A critter acts by getting a list of other actors, processing that list,
* getting locations to move to, selecting one of them, and moving to the
* selected location.
*/
public void act()
{
if (getGrid() == null)
return;
ArrayList<Actor> actors = getActors();
processActors(actors);
ArrayList<Location> moveLocs = getMoveLocations();
Location loc = selectMoveLocation(moveLocs);
makeMove(loc);
}
하지만 Actor 클래스에는 생성자가 있습니다.
public class Actor
{
private Grid<Actor> grid;
private Location location;
private int direction;
private Color color;
/**
* Constructs a blue actor that is facing north.
*/
public Actor()
{
color = Color.BLUE;
direction = Location.NORTH;
grid = null;
location = null;
}
그리고 가장 이상한 부분 은요? 이 프로그램은 완벽하게 작동하며 컴파일러는 오류를 포착하지 않습니다! 어떻게 된 일인가?
이런 종류의 질문은 실제로 print 서술문과 테스트 문으로 클래스를 작성함으로써 가장 잘 대답 할 수 있습니다. 나는 당신이 30 줄 이하의 코드로 답을 얻을 수있을 것이라고 생각합니다. 그리고 많은 세부 사항을 배울 수 있습니다. – merlin2011
** 모든 ** Java 클래스에는 최소한 하나의 생성자가 있습니다. 생성자를 선언하지 않으면 매개 변수를 사용하지 않고'super();'호출 만 포함하는 기본 생성자가 있습니다. –