J2EEOnline J2EE






Java Certification  «Prev  Next»
Lesson 4 Working with objects
ObjectiveDescribe how Objects are referenced.

Creating and using Objects in Java

An object is typically created using a constructor and the new operator.
ClassName variable = new ClassName(argumentList);
If ClassName has a field variable named field1 and a method named method1(), then field1 may be accessed as variable.field1 and method1() may be invoked as variable.method1(argumentList).

Using this and super
Java provides the this keyword to refer to the current object instance. The this keyword is used within constructors and non-static methods. When this is used within a constructor, it refers to the object being created.
When it is used within a non-static method, it refers to the object whose method is being invoked. Since static methods are not associated with an instance of a class, you should not use this within a static method.
The super keyword is similar to this, except that it refers to the superclass of the current object instance. The super keyword is used to access field variables and methods of an object's superclass that may have been hidden or overridden by those of the object's class.
Current object instance: The current object that is being executed.


this and super
this and super
The Instance program illustrates the use of this and super.
Within an instance method or a constructor, this is a reference to the current object, the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.