java - 当我们在方法之外创建对象时会发生什么?

标签 java oop object

我有一个与 OOP 相关的问题。

如果我们在方法之外创建一个对象,会有什么影响。

那个对象是全局的吗?

这是一些代码..

class A(){
 String b;
 public void c(){
  //some code in here}
 }

 class C(){

 A a = new A(); //is this ok and if it is ok what is this mean??

 public void p(){
 a.c(); //Is this possible??
}
}

最佳答案

看来您对 Java 或面向对象编程还很陌生。

在Java中创建一个对象有两个步骤:声明初始化

声明 表示您声明某物存在。 例如:String title;表示存在一个名为title的字符串对象。
初始化就是给它赋值。即:title = "Hello World!";。但是在初始化对象之前,您需要确保它已被声明。您也可以将声明和初始化结合在一个语句中:String title = "Hello World!";

对象的范围取决于您声明该对象的位置。 如果您在这样的类中声明它:

class Car {
  String name; //These are called fields
  static String author = "Farseen"
  public void doSomething() {..../*can access name and author*/}
  public static void doSomething() {..../*can access author only*/}
}

类中的所有内容都可以访问它,除了静态(我们稍后会谈到)方法。这些被称为字段
如果你在一个方法中声明它,只有那个方法可以访问它:

class Car {
  public void doSomething() {
    String name = "BMW"; //These are called local variables
  }
  public void doSomeOtherThing() {
    //Cannot acccess name
  }
}

这些被称为局部变量

如果您在类外声明它,抱歉 Java 不允许您这样做。一切都必须在一个类中。

您可以在方法外添加前缀声明,即带有访问修饰符的字段:

public :使任何人都可以访问该字段。这是合法的:
Car myCar = new Car();System.out.println(myCar.name);

private :使该字段只能由类内的方法(函数)访问。 非法 :
Car myCar = new Car();System.out.println(myCar.name);

protected :使该类的子类可以访问该字段。用户也无法访问它,例如私有(private)。

现在出现在 static 修饰符中:

它表示该字段或方法(函数)属于汽车的整个物种,而不是个别汽车。
像这样访问静态字段 author 是合法的:Car.author 无需创建单独的汽车,尽管它是合法的:new Car()。作者
静态事物只知道静态事物,不认识个体事物。

Java 中没有全局变量的概念。虽然,您可以使用这样的东西来实现它:

class Globals {
    public static String GLOBAL_VARIABLE_MESSAGE = "Hello World!";
}

并使用 Globals.GLOBAL_VARIABLE_MESSAGE 在代码中的某处使用它

希望对您有所帮助!

编辑:引用添加到问题中的代码

class A{ //Parenthesis are NOT needed
         // or allowed in class definition:
         // 'class A()' is wrong
 String b;
 public void c(){
  //some code in here
 }
}

 class C{ //Same here. No parenthesis needed
  A a = new A(); //Q: Is this ok and if it is ok what is this mean??
                 //A: Yes, completely ok.
                 // This means you added
                 // a field 'a' of type A to the class C

 public void p(){
  a.c(); //Q: Is this possible??
         //A: Of course
 }
}

关于java - 当我们在方法之外创建对象时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26283000/

相关文章:

java - Assets +skipBytes性能

java - 如何在NT3H2111 nfc芯片上选择扇区

java - RowSet 未启用写入

unit-testing - 自分流测试模式是否违反单一职责原则?

Python 面向对象编程

java - ANDROID 空指针异常错误

javascript - 如果键与数组值匹配,如何获取值

java对象引用在方法中被改变并理解结果

c++ - 在 Objective C 中添加 "->"

Java:只检查不可变对象(immutable对象)的equals()中的hashCode