在下面的程序中,我创建的2个对象创建和第二个的优势之间有什么区别

时间:2015-02-26 10:48:14

标签: java method-overriding object-reference

`In the below program ,what is the difference between the 2 Object Creation
      which i created and what is the advantage of 2nd one`
  1. 列出项目

    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();
        }
     }
    

1 个答案:

答案 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

因此,在您的示例中,ObjOb只是对某些对象的引用。两个对象都以完全相同的方式创建,唯一的区别在于您如何引用它们。

我建议您阅读有关继承的内容,您可以启动here