[英]Why we can't call 'println()' method with help of PrintStream class where out is object of this class?
[英]Why can't we call the method of the class using the class's object outside a method?
public class Basics {
Basics b = new Basics();
int instanceVariable = 0;
public void behavior() {
System.out.println("Print Something");
}
b.behavior(); // Why this line, b.behavior doesn't work?
public static void main(String[] args){
Basics b = new Basics(); /* Why are we allowed to create an
* object of same name again within
* the same class */
b.behavior(); // This line works
}
}
在上面的类中,我能够创建object。 但是我不能在任何类之外调用b.behavior
,但是我可以在一个方法中做到这一点。 为什么会这样? 有什么区别?
public class Basics1 extends Basics{
Basics b = new Basics();
Basics1 b1 = new Basics1();
b = b1.instanceVariable; // I don't see error in this line, but previous line shows //error.
b1.instanceVariable // This line doesn't work
}
为什么b1.instanceVariable
不起作用, instanceVariable
是基类实例变量。
一个类定义变量和方法。 b.behavior(); 是一个不能像这样的陈述。
您需要了解一个类是“类型定义”,而不是代码块或语句序列。
您不能只在类型定义中编写任意语句。
即使这样, "b1.instanceVariable"
也不是一个声明。 "b1.instanceVariable"
在语句上下文中没有任何意义。
所有代码都必须位于方法中,字段声明中(例如, Basics b = new Basics();
在您的示例中)或“初始化程序块”(作为构造函数的一部分或在类初始化期间运行)。
这只是一个语法规则。
在其他语言中,您可以拥有这种“原始代码”,以实现各种效果。 您想实现什么?
在任何地方编写代码并期望其执行是过程编程的一种形式。 在这种形式下,您倾向于松散上下文,并且很快该代码成为意大利面条代码->在任何地方,任何时间都可以调用的方法。
使用OOP,您将受过训练,以使用定义良好的方法创建对象,这些方法具有定义的上下文。 试想一下,什么时候您想获取b.behavior(); 被调用:在初始化类之前,在初始化类之后,在执行main之后还是销毁对象时?
有趣的是,Java为每个状态定义了语法。您可以将代码包装在{System.out.println(“ Hello World”);中。 },它将在类实例化时执行...也可以使用静态{System.out.println(“ Hello World”); },这将在加载类时执行。 但是,这又是告诉JVM何时执行的部分-约定的语法。但是在代码周围没有任何标记的情况下,您实际上希望什么时候运行?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.