通过Java中的main方法访问非静态成员 [英] Accessing non-static members through the main method in Java

查看:51
本文介绍了通过Java中的main方法访问非静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在面向对象的范例中,静态方法只能访问静态变量和静态方法.如果是这样,则会出现一个明显的问题,即Java中的main()方法如何能够访问非静态成员(变量或方法),即使它特别是公共静态void ... !!!

As a rule in object-oriented paradigm, a static method can have access only to static variables and static methods. If it is so, an obvious question arises as to how can the main() method in Java has access to non-static members (variables or methods) even though it is specifically public static void...!!!

推荐答案

main方法也无法访问非静态成员.

The main method does not have access to non-static members either.

public class Snippet
{
   private String instanceVariable;
   private static String staticVariable;

   public String instanceMethod()
   {
      return "instance";
   }

   public static String staticMethod()
   {
      return "static";
   }

   public static void main(String[] args)
   {
      System.out.println(staticVariable); // ok
      System.out.println(Snippet.staticMethod()); // ok

      System.out.println(new Snippet().instanceMethod()); // ok
      System.out.println(new Snippet().instanceVariable); // ok

      System.out.println(Snippet.instanceMethod()); // wrong
      System.out.println(instanceVariable);         // wrong 
   }
}

这篇关于通过Java中的main方法访问非静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆