[英]How can I run code upon instantiating a class?
How can I run code when a new object is created, without having to perform any separate calls? 创建新对象时,如何执行代码而不必执行任何单独的调用? In other words, how can I define what happens during the creation of an object?
换句话说,如何定义对象创建期间发生的情况?
For example: 例如:
class Apple {
//code here
}
// ...
Apple banana = new Apple();
// ...
How can I automatically run code at the time I call this: 调用此代码时如何自动运行代码:
Apple banana = new Apple();
For example, how can I make one of Apple
's methods be called at the time I create the new Apple
? 例如,在创建新的
Apple
如何调用Apple
的方法之一? Coming from Python, I'm looking for something like __init__
. 来自Python,我正在寻找类似
__init__
东西。
Add a constructor to your Apple
class: 向您的
Apple
类添加一个构造函数:
class Apple {
public Apple () {
//Your code here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.