比方说,我有一段代码:将子类的构造函数提供给父类的对象有什么意义?
class one
{
String one = "First";
}
class sec extends one
{
String sec = "Second";
}
class num
{
public static void main(String[] args)
{
one o = new one();
sec s = new sec();
one oo = new sec();
// the object will be of that class for which we are providing the reference
// then what is the use of the constructor
sec s = new one(); // this is not working
System.out.println(o.one);
System.out.println(s.sec);
System.out.println(oo.one); # this seems right
System.out.println(oo.sec); # this is not working
}
}
我被参考和构造函数在创建对象混淆。 我已将sec
类扩展为从类one
继承。 我得到了我们引用one
类的前两个对象创建的含义,并为第二个对象创建了相同的对象。
但是第三个对象呢?我们正在使用第一类的引用并提供子类的构造函数,我可以使用第三个对象(oo)来引用一个类的变量和方法而不是第二类。
如果我必须使用一个类的方法和变量,那么我可以将它与对象(o)而不是对象(oo)一起使用。那么当两个对象表现得像对方一样时,两个对象之间有什么区别呢?
one o = new one();
one oo = new sec();
我想知道这两个是什么改变来当我们使用子类的构造函数,而不是基类之间的差异。
好的,我会看到谢谢先生:-) – babygame0ver
肯定会看看多态性。这也不是JAVA特有的。对于任何OOP你都会很有用。 – Tom
@AkshaySingh在发布新问题之前,请在网站上搜索所有未来的问题。有可能你的问题已经被回答了。 – CKing