简体   繁体   English

如果构造函数被声明为不完整类型会怎样?

[英]What happens if constructor is declared an incomplete type?

Just being curious. 只是好奇。 Having the following simple class: 具有以下简单的类:

public class Foo {
   private static int fooVar = 1;
   private int foo;
   private int boo = 1; // another int, not a typo
   public Foo(int foo) {
      this.foo = foo;  
   }
}

Calling: 致电:

Foo a, b, c;

Which one is declared first? 首先声明哪个? (I assume from the lft to the right.) Are instance variables fooVar and foo declared too? (我假设从右边的lft开始。)是否也声明了实例变量fooVarfoo What happens in the memory? 内存中会发生什么? Is the value of variable boo saved in the memory even the constructor haven't been called at all? 即使根本没有调用构造函数,变量boo的值是否也会保存在内存中?

Nikolas, 尼古拉斯,

a,b and c are pointers of type Foo. a,b和c是Foo类型的指针。 They should be, as you said, declared from left to right. 正如您所说,应该从左到右声明它们。

because is the same as declaring 因为和声明一样

Foo a; oo

Foo b; Foo b;

Foo c; Foo c;

What happens in the memory? 内存中会发生什么? Is the value of variable boo saved in the memory even the constructor haven't been called at all? 即使根本没有调用构造函数,变量boo的值是否也会保存在内存中?

There is no such value boo or foo (typo?). 没有这样的值boo或foo(typo?)。

If the constructor has not been called, there is no object yet in your code. 如果尚未调用构造函数,则代码中还没有对象。

If do this: 如果这样做:

Foo a= new Foo();

You are actually doing 2 things, in the following order: First a Foo object is created, then it is a asigned to Foo pointer a. 您实际上是按照以下顺序做两件事:首先创建一个Foo对象,然后将其分配给Foo指针a。

Remember your constructor is like a method. 记住您的构造函数就像一个方法。 Please add () before { And if you are passing a input variable, please do so inside the () like: 请在{之前加上(),如果要传递输入变量,请在()内部添加,例如:

public Foo(foo) {
      this.foo = foo;  }

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

相关问题 当一起处理和声明异常时会发生什么? - What happens when an exception is handled and declared together? Java 中声明的未初始化变量会发生什么? - What happens to a declared, uninitialized variable in Java? 如果接口不能具有构造函数,那么会发生什么? - If interface cannot have a constructor, what happens here? 如果我的 bean 被声明为 @ApplicationScoped ,但它有一个公共字段,会发生什么? - What happens if my bean is declared @ApplicationScoped , but it has a public field? Java generics 类型擦除:何时以及会发生什么? - Java generics type erasure: when and what happens? 如果bean尝试在其构造函数中加载Spring应用程序上下文,会发生什么? - What happens if a bean attempts to load the Spring application context in its constructor? 当子类没有在Java中定义构造函数时会发生什么? - What happens when subclasses don't define a constructor in Java? 调用构造函数时会发生什么情况(在此上下文中为清晰的概念)? - What happens when a call made to an constructor (clear concept in this context)? Guice:当我在构造函数上使用过多的 @Inject 时会发生什么 - Guice: what happens when I have excessive @Inject on a constructor Java在构造函数中为成员分配数组参数时会发生什么? - Java what happens when I assign an array argument to a member in constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM