静态方法访问非静态构造函数? [英] Static method access to non-static constructor?

查看:275
本文介绍了静态方法访问非静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天有一个考试Java。


$ b >
  • 静态方法不能调用非静态方法。

  • 构造函数是一种不带返回类型的方法

      public class Main {
    public static void main(String [] args){
    Main p = new Main();
    k();
    }

    protected Main(){
    System.out.print(1234);
    }

    protected void k(){
    }
    }





      Main p = new Main()line prints 1234 
    k()行引发错误


  • 那么为什么会发生?它不会与上面的Java规则冲突吗?

    解决方案


    1 - 静态方法不能调用非静态方法。


    当然可以,但需要一个对象来调用



    在静态方法中,没有引用可用,因此 foo (相当于 this.foo())是非法的。


    2 - 构造函数是一种没有返回类型的方法。


    如果它们应该与方法比较,我会说构造函数更接近非方法,静态方法(因为构造函数中有一个引用)。



    ,你应该清楚为什么一个静态方法可以调用一个构造函数没有任何问题。






    up:

      Main p = new Main(); 

    可以,因为 new Main()不依赖任何现有的对象。

      k(); 

    不行,因为它等效于 this.k code>和在您的(静态)main方法中不可用。


    I had an exam yesterday on Java. There is something which seem really ambiguous to me.

    Rules are simple:

    1. Static method cannot cannot call non-static methods.
    2. Constructors are kind of a method with no return type.

      public class Main {
          public static void main(String[] args) {
              Main p = new Main();
              k();
          }
      
          protected Main() {
              System.out.print("1234");
          }
      
          protected void k() {
          }
      }
      

      Main p = new Main() line prints 1234
      k() line raises error
      

    So why did this happen? Doesn't it conflict with the rules of Java above?

    解决方案

    1 - Static method cannot cannot call non-static methods.

    Sure they can, but they need an object to call the method on.

    In a static method, there's no this reference available, so foo() (which is equivalent to this.foo()) is illegal.

    2 - Constructors are kind of a method with no return type.

    If they should be compared to methods, I would say constructors are closer to non-static methods (since there is indeed a this reference inside a constructor).

    Given this view, it should be clear to you why a static method can call a constructor without any problems.


    So, to sum it up:

    Main p = new Main();
    

    is okay, since new Main() does not rely on any existing object.

    k();
    

    is not okay since it is equivalent to this.k() and this is not available in your (static) main method.

    这篇关于静态方法访问非静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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