Home  >  Q&A  >  body text

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 days ago700

reply all(3)I'll reply

  • 天蓬老师

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

    new will call the constructor,

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

    If you use the new Demo 这个时候会去调用Demo()这个构造方法也就是会输出。但是new run()不会,因为构造方法没有调用输出语句,要输出需要去调用print() method.

    reply
    0
  • 迷茫

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

    The second output is the "first code block", right?

    reply
    0
  • 巴扎黑

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

    You need to understand these concepts:

    • Construction method

    • Static methods

    • Instance methods

    • Code Blocks

    After understanding these, you will understand

    reply
    0
  • Cancelreply