简体   繁体   English

为什么我们不能在方法之外使用类的对象来调用类的方法?

[英]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
        }


}

In the above class, I am able to create object . 在上面的类中,我能够创建object。 But I can't call b.behavior outside any class, but I am able to do that within a method. 但是我不能在任何类之外调用b.behavior ,但是我可以在一个方法中做到这一点。 Why is that so? 为什么会这样? What is the difference? 有什么区别?

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


}

Why is b1.instanceVariable not working, instanceVariable is the base class instance variable. 为什么b1.instanceVariable不起作用, instanceVariable是基类实例变量。

A class defines variables and methods. 一个类定义变量和方法。 b.behavior(); b.behavior(); is a statement that cannot be on its own like that. 是一个不能像这样的陈述。

You need to understand that a class is a "type definition", not a code block or sequence of statements. 您需要了解一个类是“类型定义”,而不是代码块或语句序列。

You cannot just write arbitrary statements in a type definition. 您不能只在类型定义中编写任意语句。

Even so, "b1.instanceVariable" is not a statement. 即使这样, "b1.instanceVariable"也不是一个声明。 "b1.instanceVariable" doesn't mean anything in statement context. "b1.instanceVariable"在语句上下文中没有任何意义。

All code needs to be in methods, in field declarations (such as Basics b = new Basics(); in your example) or in "initializer blocks" (which are run as part of constructors or during class initialization). 所有代码都必须位于方法中,字段声明中(例如, Basics b = new Basics();在您的示例中)或“初始化程序块”(作为构造函数的一部分或在类初始化期间运行)。

This is just a syntax rule. 这只是一个语法规则。

In other languages, you can have this kind of "raw code", to achieve various effects. 在其他语言中,您可以拥有这种“原始代码”,以实现各种效果。 What do you want to achieve? 您想实现什么?

  • run during compilation (like in Perl): Cannot be done in Java 在编译期间运行(如在Perl中):无法在Java中完成
  • run during constructor: use an init block 在构造函数中运行:使用init块
  • run during class loading: use a static init block 在类加载期间运行:使用静态init块
  • run when the program starts: put it in static void main 在程序启动时运行:将其放在static void main中
  • run during method invokation: put it in that method 在方法调用期间运行:将其放入该方法

Write code anywhere and expect it to execute is a form of procedural programming. 在任何地方编写代码并期望其执行是过程编程的一种形式。 In this form , you tend to loose context and soon the code becomes a spaghetti code --> methods getting called anywhere , anytime. 在这种形式下,您倾向于松散上下文,并且很快该代码成为意大利面条代码->在任何地方,任何时间都可以调用的方法。

With OOP, you are trained to create objects with well defined methods which have a defined context. 使用OOP,您将受过训练,以使用定义良好的方法创建对象,这些方法具有定义的上下文。 Just think, when would you like to get the b.behavior(); 试想一下,什么时候您想获取b.behavior(); being called : Before initializing a class, after initializing the class, after execution of main or when the object is destroyed? 被调用:在初始化类之前,在初始化类之后,在执行main之后还是销毁对象时?

Interestingly, Java has defined syntaxes for each of the states.. You can wrap your code in { System.out.println("Hello World "); 有趣的是,Java为每个状态定义了语法。您可以将代码包装在{System.out.println(“ H​​ello World”);中。 } and it will execute when the class is instantiate...Also you can use static { System.out.println("Hello World "); },它将在类实例化时执行...也可以使用静态{System.out.println(“ H​​ello World”); } and this will execute when class is loaded. },这将在加载类时执行。 But again, this is part of telling the JVM when to do it - an agreed upon syntax.. But without any marker around your code, when would you actually expect to run? 但是,这又是告诉JVM何时执行的部分-约定的语法。但是在代码周围没有任何标记的情况下,您实际上希望什么时候运行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们不能在PrintStream类的帮助下调用'println()'方法,其中out是这个类的对象? - Why we can't call 'println()' method with help of PrintStream class where out is object of this class? 为什么我们不能在 java 的子 class 的方法之外访问 class 内部的父实例变量 class? - why can't we access parent class instance variables inside the class outside the method in child class in java? 我们可以使用类的引用来调用方法吗 - Can we call method using the reference of the class 外部类的调用方法 - Call Method Outside Class 为什么我不能在同名的匿名类之外调用方法 - Why can't I call a method outside of an anonymous class of the same name 我们可以为字符串调用Object类的toString()方法吗 - can we call the toString() method of the Object class for a String 为什么我不能在声明方法之外访问本地类? - Why can't I access local class outside declaring method? 为什么我不能在类之外的方法中使用数组? - Why can't I an array in a method outside its class? 为什么不能在同一个包中调用另一个类的包私有方法呢? - Why can't I call a package-private method of another class that's a subclass of a class in the same package? 为什么我们不能在扩展类的静态方法中使用此实例? - Why can't we use this instance in the static method of extended class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM