简体   繁体   English

Java:如何使用类名直接调用方法

[英]Java: how it is possible to call method directly using class name

As i know whenever we want to call any method then we create object and invoke its method using obj.methodname . 据我所知,只要我们想调用任何方法,就创建对象并使用obj.methodname调用其方法。

But below program calls the method of E class without creating object. 但是下面的程序在不创建对象的情况下调用E类的方法。 How this is possible? 这怎么可能? Please anyone help me to understand this concept. 请任何人帮助我理解这个概念。

I mean 'From below code, how this is possible to write E.test2(); 我的意思是 “从下面的代码中,如何编写E.test2(); ? , i think it should be E obj=new E(); obj.test2(); ,我认为应该是E obj=new E(); obj.test2(); E obj=new E(); obj.test2();

    class E
{
    int i;
    static int j;

    void test1()
    {
        System.out.println("From test1");
    }
    static void test2()
    {
        System.out.println("From test2");
    }
}

class F extends E
{
    int m;
    static int n; 
    void test3()
    {
        System.out.println("From test3");
    }
    static void test4()
    {
        System.out.println("From test4");
    }
}

public class G {
    public static void main(String args[])
    {
        E.test2();
        F.test2();
    }
}  

The method E.test2 is declared as static which means that you can use this method without create an instance of that class. 方法E.test2被声明为static ,这意味着您可以使用此方法而无需创建该类的实例。 There are so many classes in Java that uses it. Java中有很多使用它的类。

See the docs: 参见文档:

Understanding Instance and Class Members 了解实例和类成员

static methods can be called using class name and do not require an object of that class. 可以使用类名称调用静态方法,并且不需要该类的对象。

Please read this: http://introcs.cs.princeton.edu/java/21function/ 请阅读以下内容: http : //introcs.cs.princeton.edu/java/21function/

test2 method is static in class E , and static method are class specific not object specific ,and they are accessed using "classname.methodname" syntax. test2方法在类E中是静态的,而静态方法是特定于类的,而不是特定于对象的,并且使用“ classname.methodname”语法进行访问。 where methodname is static method of "classname" 其中methodname是“类名”的静态方法

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

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