所以我有这个类:如何从一个子类中的Java
,然后我也
public class son extends parent {
public son(int id,int row) {
super(id,son);
}
}
的问题是我如何创建该类延伸父对象类班子。我必须这样称呼它:
son x=new son(int id,int row);
我真的很困惑。
所以我有这个类:如何从一个子类中的Java
,然后我也
public class son extends parent {
public son(int id,int row) {
super(id,son);
}
}
的问题是我如何创建该类延伸父对象类班子。我必须这样称呼它:
son x=new son(int id,int row);
我真的很困惑。
是的,你只是在现场!要说得很清楚,在调用构造函数时,您不会使用id
和row
的类型,您只需提供该类型的值即可。
因此,这是错误的:
son x = new son(int 5, int 6); //Incorrect
这是正确的:
son x = new son(5, 6); //Correct
您也可以通过正确类型的变量,就像这样:
int id = 5;
int row = 6;
son x = new son(id, row);
而且,我刚刚注意到你写道:
public class parent {
private int id;
private id row;
//....
代替
public class parent {
private int id;
private int row; //Note the change id --> int here
//....
如果这是一个错字,别担心。否则,你可能会有一个概念误解。 id
不是一种类型,但是int
是。所以我们不能将row
声明为id
,但我们可以声明它为int
。与C
和朋友不同,您不能使用typedef
创建类型的同义词,因此您坚持使用基本类型(int
,boolean
等)。
因为你看起来你是Java的新手,所以这个约定对于类有代词情况(首字母大写的第一个字母)的名字。因此,这将是更好的风格来使用你的类以下格式:
public class Parent {
private int id;
private int row;
public Parent(int id,int row) {
this.id=id;
this.row=row
}
}
public class Son extends Parent {
public Son(int id,int row) {
super(id,son);
}
}
public class ThisClassHasManyWordsInItAndItShouldBeFormattedLikeThis {
//.....
}
然后使建设:
Son x = new Son(5,6);
一旦你已经构建了Parent
对象像Parent p = new Parent(4,5);
,有没有办法将p
更改为Son
。这是不可能的。但是,您可以复制p
到一个新的Son
,你可以做一些修改类,使之更容易使这些副本:
public class Parent {
private int id;
private int row;
public Parent(int id,int row) {
this.id=id;
this.row=row
}
public int getId() {
return id;
}
public int getRow() {
return row;
}
}
public class Son extends Parent {
public Son(int id,int row) {
super(id,son);
}
public Son(Parent p) {
super(p.getId(), p.getRow());
}
}
现在,我们可以创建一个家长,并复制它进入一个新的儿子:
Parent p = new Parent(4,5);
Son s = new Son(p); //will have id of 4 and row of 5
值得一提的是,虽然这一切都很好,学习类扩展是如何工作的,你不实际使用我很正确。通过说,你是说Son
是Parent
的一种,这在家庭的小学模型中是不正确的。一个更好的办法,以一个家庭模式很可能是:
public class Person {
private Person mother;
private Person father;
public Person(Person mother, Person father) {
this.mother = mother;
this.father = father;
}
}
如果你还在寻找一种方式,包括类扩展,然后Man
和Woman
有意义的Person
类的扩展,因为Man
是类型Person
。 (即所有男人都是人,不是所有人都是男人)。
public class Person {
private Man father;
private Woman mother;
public Person(Man father, Woman mother) {
this.father = father;
this.mother = mother;
}
}
public class Man extends Person {
public Man(Man father, Woman mother) {
super(father, mother);
}
}
public class Woman extends Person {
public Woman(Man father, Woman mother) {
super(father, mother);
}
}
是的,你可以调用它的方式..或者你可以使用父母的引用来引用子类的实例 – TheLostMind
我真的不喜欢下壳类命名。 – OPK
将类型排除在外,否则您的语法应该起作用。儿子x =新儿子(id,row); – nicomp