`In the below program ,what is the difference between the 2 Object Creation
which i created and what is the advantage of 2nd one`
列出项目
class Overload {
void sample() {
System.out.print("Sample ");
}
void demo(int a) {
System.out.print("parent a: " + a);
}
void demo(int a, int b) {
System.out.print("parent a and b: " + a + "," + b);
}
double demo(double a) {
System.out.print("parent double a: " + a);
return a * a;
}
}
class Overload_1 extends Overload {
void demo(int a) {
System.out.print("Child a: " + a);
}
void demo(int a, int b) {
System.out.print(" Child a and b: " + a + "," + b);
}
double demo(double a) {
System.out.print("Child double a: " + a);
return a * a;
}
}
class Change_Reference {
public static void main(String args[]) {
Overload_1 Obj = new Overload_1(); //What is the of this Object
Overload Ob = new Overload_1();//What is the use of this Object
double result;
Obj.demo(10);
Obj.demo(10, 20);
result = Obj.demo(5.5);
System.out.print("O/P : " + result);
Obj.sample();
}
}
答案 0 :(得分:0)
继承是一个"是一个"关系。让我们使用狗/动物的例子:
public class Animal {
public void run() {
// ...
}
}
public class Dog extends Animal {
public void bark() {
// ...
}
}
狗是一种动物,所以这些都是有效的:
Animal animal = new Dog();
Dog dog = new Dog();
所以这些调用都是有效的:
animal.run();
dog.run();
dog.bark();
但是,animal
的类型为Animal
,其中没有bark()
方法。狗是动物,但你把它称为动物,而不是狗,所以你不知道它可以吠叫。例如,animal
可能是猫。这意味着此调用将产生编译错误:
animal.bark(); // compile-time error, no such method in class Animal
因此,在您的示例中,Obj
和Ob
只是对某些对象的引用。两个对象都以完全相同的方式创建,唯一的区别在于您如何引用它们。
我建议您阅读有关继承的内容,您可以启动here