简体   繁体   English

具有main方法的Java继承类

[英]Java Inheritance classes with main method

I have 2 objects defined 我定义了2个对象

In Object-1, When I reference the child object it invokes the child method m1() whereas in Object-2 when I reference the child method m1() it references the Parent object.. 在对象1中,当我引用子对象时,它将调用子方法m1();而在对象2中,当我引用子方法m1()时,它将引用父对象。

In both the cases I assume parent object will hold a child type object at runtime... 在这两种情况下,我都假定父对象将在运行时保存子类型对象...

Object-1 对象1

    package pkgB;

    class Parent{
        static int i = 10;
        void m1(){
            System.out.println("In Parent = " + i);
        }

        static void m1(String s){
            System.out.println(s +i );
        }
    }

    public class Child extends Parent{
        static int i = 20;
        void m1(){
            System.out.println("In child" + Child.i);
        }
        public static void main(String[] args){
            Parent p = new Child();
            p.m1();

        }
    }

Object-2 对象2

package pkgB;



class Drink{
    public static void m1(){
        System.out.println("Im Drink method");
    }

}

class Coffee extends Drink{
    public static void m1(){
        System.out.println("Im Coffee method");
    }

}

public class test {

    public static void main(String[] args) {
        Drink d = new Coffee();
        d.m1();

    }
}

Output Dobject-1: 输出Dobject-1:

In child20

Output Dobject-2: 输出Dobject-2:

Im Drink method

static methods are called by their Type while instance methods are called based on the object type. 静态方法按其类型调用,而实例方法则根据对象类型进行调用。 static methods are not overriddedn . 静态方法不会被覆盖

When you say, 当你说,

  Parent p = new Child();
  p.m1();

You are creating reference type of Parent but object type of Child . 您正在创建Parent对象的引用类型,但创建Child对象的对象类型。 m1() is instance method so it is overridden and the Child method is called because object is of type Child m1()是实例方法,因此它被覆盖,并且调用Child方法,因为对象的类型为Child

But when you say, 但是当你说

  Drink d = new Coffee();
  d.m1();

here, m1() is static method which are bound to class type. 在这里, m1()是绑定到类类型的static方法。 So d.m1() will call the static method as d is of type Drink 所以d.m1()将调用static方法,因为dDrink类型

In your second example, the m1() methods are static methods. 在第二个示例中, m1()方法是静态方法。 Your compiler should give you a warning when you execute d.m1() , something about referring to a static method in a non-static way. 执行d.m1() ,编译器应向您发出警告,这与以非静态方式引用静态方法有关。

Anyway, when you call d.m1() in the second example, you are really calling Drink.m1() since d is declared a Drink . 无论如何,当你调用d.m1()在第二个例子中,你真的叫Drink.m1()因为d被宣布为Drink

Calling static method using reference variable means you are in state of Sin :) 使用引用变量调用静态方法意味着您处于Sin状态:)

static methods/variables are solely part of class and can not be overriden. 静态方法/变量仅是类的一部分,不能被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM