Topic: 请各位多指教

  Print this page

1.请各位多指教 Copy to clipboard
Posted by: 841221
Posted on: 2009-04-13 20:25

在父类中怎么样调用子类的方法和对象?
谢谢!

2.Re:请各位多指教 [Re: 841221] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2009-04-20 17:33

Suppose that you have a parent/derived class hierarchy like this:

public class ParentClass
{
// I want to invoke fields and methods of the DerivedClass.
public void method1()
{
DerivedClass object = new DerivedClass();
object.int1;
object.method2();
}
}

class DerivedClass extends ParentClass
{
public static final int int1 = 10;
public void method2()
{
System.out.println("Hello, I am a method in the DerivedClass");
}
}


Invoking the methods and fields defined in a derived class from a parent class is Not recommended and is often thought to be a bad idea/design. Because one of the most important object-oriented feature (i.e. polymorphism) no longer works in the parent class. (The example above demonstrates this idea.) Or the parent now is tightly coupled with the derived class.

Unless you have a very specific reason to invoke methods in the derived class, it is recommended not to do so.

Thanks,
Jiafan

3.Re:请各位多指教 [Re: 841221] Copy to clipboard
Posted by: 841221
Posted on: 2009-04-23 15:55

谢谢了!


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923