日安!
我正在回顾Java的概念。并编写了以下代码:
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.eat();
dog.sleep();
}
}
abstract public class Animal {
private int age;
public Animal (){
age = 1;
}
public Animal (int age){ //How can I call this constructor?
this.age = age;
}
public void eat(){
System.out.println("Eat");
}
abstract public void sleep();
}
abstract public class Canine extends Animal{
abstract public void roam();
}
public interface Pet {
public String petName = null; //i want the pets to have a variable petName.
public void trick();
}
public class Dog extends Canine implements Pet{
public void roam(){
System.out.println("roam");
};
public void sleep(){
System.out.println("sleep");
};
public void eat(){
System.out.println("Eat Dog");
};
public void trick(){
System.out.println("trick");
}
}我有以下几个问题:
我怎么叫动物过载的constructor?
提前谢谢你。
发布于 2011-04-07 05:10:50
一些解决办法:
public interface Pet {
String getName();
void trick();
}现在,Dog类(或实现宠物的任何类)都必须实现Pet.getName()。给Dog类一个名为'name‘的字符串类型的字段,并从Dog.getName()中返回它。
public abstract class Canine extends Animal {
public Canine(int age) {
super(age); // pass the age parameter up to Animal
}
...
}
public class Dog extends Canine implements Pet {
private final String name;
public Dog(String name,int age) {
super(age); // call the age constructor
this.name=name;
}
public String getName() { return name; }
... rest of class ...
}每个子类(尤指))将需要为所有要调用的父类构造函数提供匹配的构造函数!(因此,我向Canine构造函数中添加了age参数,以便Dog可以向它传递一个age参数。
发布于 2011-04-07 05:23:40
看看这个,也许对你有帮助,
http://www.roseindia.net/java/beginners/constructoroverloading.shtml
http://www.jchq.net/certkey/0602certkey.htm
发布于 2011-04-07 05:10:10
1)你可以称之为“这(20)”;
显式此构造函数调用的示例
公共类点{
int mx;
我的;
//============ Constructor
public Point(int x, int y) {
mx = x;
my = y;
}
//============ Parameterless default constructor
public Point() {
this(0, 0); // Calls other constructor.
}
. . .}Super(.)-一个对象的超类(父)构造函数有它自己的类的字段,加上它的父类、祖父母类的所有字段,一直到根类对象。必须初始化所有字段,因此必须调用所有构造函数!Java编译器在构造函数链接过程中自动插入必要的构造函数调用,或者您可以显式地执行它。
如果没有构造函数调用作为构造函数的第一条语句,Java编译器将插入对父构造函数(super)的调用。以下是上面所述的构造物。
//============ Constructor (same as in above example)
public Point(int x, int y) {
super(); // Automatically done if you don't call constructor here.
m_x = x;
m_y = y;
}Why you might want to call super explicitly通常,您不需要调用父类的构造函数,因为它是自动生成的,但是有两种情况需要这样做。
您希望调用具有参数的父构造函数(自动生成的超级构造函数调用没有参数)。没有无参数的父构造函数,因为父类中只定义了带有参数的构造函数。
https://stackoverflow.com/questions/5576249
复制相似问题