首頁  >  問答  >  主體

java - 创建变量没有输出??

class Car
{
    int num;
    String color;

    public static void run()
    {
        System.out.println("行驶");
    }

}

class Demo99 
{
    public static void main(String[] args) 
    {
    Car baoma = new Car();
//这这儿为什么需要使用baoma.run();这个语句才有输出呢?
//下面的代码不需要引用函数就可以得到输出了

    }
}

这个代码没有输出这是为什么呢??
下面这个代码

public class CodeBlock02
{
    {
      System.out.println("第一代码块");    
    }
    
    public CodeBlock02()
        {
        System.out.println("构造方法");
        }
        
        {
          System.out.println("第二构造块");
        }
     public static void main(String[] args)
        {
          CodeBlock02 acv = new CodeBlock02();  
//或者用这个都有输出
          new CodeBlock02();
        }
}    
PHP中文网PHP中文网2742 天前697

全部回覆(3)我來回復

  • 天蓬老师

    天蓬老师2017-04-18 10:55:38

    new 會去呼叫構造方法,

    
        public class Demo{
            public Demo(){
                System.out.println("demo");
            }
        }
        public class Run{
            public Run(){
            }
            
            public void print(){
                System.out.println("run");
            }

    如果你使用了new Demo 这个时候会去调用Demo()这个构造方法也就是会输出。但是new run()不会,因为构造方法没有调用输出语句,要输出需要去调用print()方法。

    回覆
    0
  • 迷茫

    迷茫2017-04-18 10:55:38

    第二個輸出的是「第一個程式碼區塊」吧?

    回覆
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:55:38

    你要理解這幾個概念:

    • 構造方法

    • 靜態方法

    • 實例方法

    • 程式碼區塊

    了解了這幾個, 你就想明白了

    回覆
    0
  • 取消回覆