我对这个话题很困惑。 //一个类(比如说B)分别扩展或实现另一个类或接口(interface)
interface myInterfaceA{
int interfaceDataMember1;
int interfaceDataMember2;
void interfaceMethod1();
void interfaceMethod2();
}
class myClassA{
int parentClassDataMember1;
int parentClassDataMember2;
myclassA(){}
void parentClassMethod1(){}
void parentClassMethod2(){}
}
//情况1
class B implements myInterfaceA{
int dataMember1;
int dataMember2;
B(){}
void method1(){}
void method2(){}
}
//或情况2
class B extends myClassA{
int dataMember1;
int dataMember2;
B(){}
void method1(){}
void method2(){}
}
//那么无论哪种情况,通过以下方式创建 B 类对象的目的是什么
myInterfaceA objectB = new B();
// or
myClassA objectB = new B();
1) 这个程序有名称吗? 2)什么(数据成员、方法、构造函数)将被加载到objectB中? 3)如果B类的所有代码都会被加载到objectB中,那么为什么我们要给出接口(interface)或父类的引用呢? 4)这是否表明多态性?如果是,那为什么? 5)在case2中,B类也会继承myClassA的构造函数 6)为什么创建子类对象时也会调用父类的构造函数
最佳答案
1) is there any name of this procedure?
这就是多态性。
2) what (data memeber, methods, constructor ) will be loaded in objectB?
每个数据成员和方法都将被objectB继承。
对于接口(interface),数据成员是private
、static
、final
常量。它们必须在构造函数中初始化。这些方法必须由类 B 实现。
对于父类(super class),数据成员和方法只是继承。您可以重写这些方法。变量不是多态的。
3) if all the code of class B will be loaded in the objectB then why did we give the refrece of interface or parent class?
我们提供接口(interface)或父类的引用,以便在有多个子类型的情况下,我们可以有一个接受父类(super class)型的方法,而不是创建多个方法。这减少了代码行并使代码可读。
4) is this shows polymorphism? if yes, then why?
这显示了多态行为,因此您不需要将每个子类型绑定(bind)到不同的方法。可以编写一个方法来动态绑定(bind)单个父类(super class)型的所有子类型。
5) in case2 will class B also inherit the constructor of myClassA
构造函数不是继承的。如果需要,您必须显式调用 super()。
6) why the constructor of parentclass is also called whe we create child class object
并不强制每次都调用父类的构造函数。如果不需要,您可以跳过它。但作为标准做法,super()
是子类构造函数的第一行,因此父类(super class)对象创建中的任何更改都不会影响子类。
关于java - 使用不同的引用创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813016/