Section 9 Constructor

本文深入探讨了Java中的堆和栈的概念,解释了实例变量与局部变量的区别,并详细阐述了构造器的使用方式及垃圾回收机制的重要性。通过解析Java内存分配与释放的过程,帮助开发者理解如何更有效地管理内存资源。

Stack and Heap:

Stack: method invocations and local variables.

Heap: all objects (instance variables inside), no matter the reference is a local or instance variable.


Instance variables: declared inside a class but not inside a method.

Local variables: declared inside a method, including method parameters.


Constructor:

The only outside way to invoke a constructor is with the keyword new.

You must write a no-arg constructor if you have written(overloaded) an arg constructor and want to use a no-arg constructor.

All the constructors in an object's inheritance tree must run when you make a new object.

When invoking a constructor, it first calls its super constructor way up to Object. So in every constructor, the compiler by default puts the no-arg super constructor super() as the first statement if you don't.

Superclass part is always completely built before the subclass can be constructed.

You can call this() in a constructor to invoke another constructor. A constructor can have a call to super() or this(), but never both.


Garbage Collection:

Your job is to make sure that you abandon objects when you're done with them.


### 创建对象及构造函数的用法 在ABAP编程环境中,类定义通过`CLASS`语句实现。创建对象实例通常涉及使用`CREATE OBJECT`指令或`NEW`操作符[^1]。 #### 使用 `CREATE OBJECT` 当采用`CREATE OBJECT`来初始化一个新对象时,语法如下所示: ```abap DATA: lo_my_object TYPE REF TO zcl_my_class. CREATE OBJECT lo_my_object. ``` 此方法适用于不带参数传递给构造器的情况;如果需要向构造器提供参数,则应考虑使用`NEW`关键字的方式。 #### 使用 `NEW` 关键字 对于带有输入参数的构造器调用,推荐的做法是利用`NEW`操作符,它允许更直观地指定初始属性值或执行其他必要的设置动作: ```abap DATA(lo_another_instance) = NEW zcl_my_class( iv_param1 = 'value' ). ``` 这里展示了如何直接在声明的同时完成对象构建并赋初值的过程。值得注意的是,在现代版本的SAP系统里,这种方式被广泛采纳因为其简洁性和可读性强的特点。 #### 定义构造方法 为了自定义对象创建过程中的行为逻辑,可以在类内部定义名为`constructor`的方法作为特殊成员函数用于处理此类需求。下面是一个简单的例子说明怎样编写自己的构造器以便接收外部传入的数据项并对它们加以保存: ```abap CLASS zcl_sample DEFINITION. PUBLIC SECTION. METHODS: constructor IMPORTING value(iv_input) TYPE string. ENDCLASS. CLASS zcl_sample IMPLEMENTATION. METHOD constructor. " Store passed parameter into an attribute or perform initialization tasks here me->mv_attribute = iv_input. ENDMETHOD. ENDCLASS. ``` 上述代码片段中展示了一个接受字符串类型的单个参数并通过将其存储到私有变量`mv_attribute`内完成了基本的对象状态设定工作流程。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值