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();}}
问题解答
回答1: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()方法。
回答2:第二个输出的是“第一代码块”吧?
回答3:你要理解这几个概念:
构造方法
静态方法
实例方法
代码块
了解了这几个, 你就想明白了
相关文章:
