Lecture 3 Methods and Constructors
Lecture 3 Methods and Constructors
Special Methods
✓ main() method
✓ constructors
main() method
• Execution starts from main() method
• main is defined as
public static void main(String[] args)
Special Methods
✓ main() method
✓ constructors
Constructors
• Constructors are a special kind of methods that are invoked to construct objects
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• A constructor with no parameters is referred to as a no-argument constructor (parameter
less constructor)
✓ Constructors are invoked using the new operator when an object is created.
new ClassName();
Example
new Circle(); // creating object using no argument constructor
new Circle(5.0); // creating object using parameterized constructor
Default Constructor
* A no-arg constructor with an empty body is implicitly declared in the
class, if class is declared without constructors.
* This is called default constructor
* This provided automatically only if no constructors are explicitly
declared in the class.
Reference Variables and Reference Types
* If a data field of a reference type does not reference any object, the data field
holds a special literal value, null
Accessing Object’s data and methods via reference variables
✓Used to
• To refer to hidden data field of the class
• To enable a constructor to invoke another
constructor of same class (statement that uses the
keyword this appear first in the constructor)
this keyword
class This{
int i;
public This(){
this(5); Invoking parameterized constructor
}
public This(int i){
this.i=i; Referring hidden data member i
}
public void show(){
System.out.println("i = "+i);
}
} public This(int x){ public This(int x){
Equivalent to
public class DemoThis{ x=i; this.x=i;
public static void main(String[] a){ } }
This t1 = new This();
t1.show();
This t2 = new This(20);
t2.show();
}
}