Java 1.1 Worksheet
Java 1.1 Worksheet
What is a Constructor?
A constructor in Java is similar to a method that is invoked when an object of the class is
created.
Unlikes Java Method, a constructor has the same name as that of the class and does not
have any return type. For example,
class Test {
Test() {
// constructor body
}
}
Here, Test() is a constructor. It has the same name as that of the class and doesn't have a
return type.
Types of Constructor:-
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
Topic:1.
Write a Program to understand the concept of No-Arg Constructor
Program Code:
Similar to methods, a Java constructor may or may not have any parameters (arguments).
private Constructor() {
// body of the constructor
}
class Main {
int i;
Output:
Explanation:
In the above example, we have created a constructor main(). Here, the constructor does not
accept any parameters. Hence, it is known as a no-arg constructor.
Topic:2
Write a Program to understand the concept of Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructor with parameters).
Program Code:
class Main {
String languages;
Output:
Explanation:
In the above example, we have created a constructor named main(). Here, the constructor
takes a single parameter. Notice the expression,
Here, we are passing the single value to the constructor. Based on the argument passed, the
language variable is initialized inside the constructor.
Topic:3.
If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.
Program Code:
class Main {
int a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
Explanation:
Here, we haven't created any constructors. Hence, the Java compiler automatically creates
the default constructor.
The default constructor initializes any uninitialized instance variables with default values.
Learning outcomes (What I have learnt):
• Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java compiler
if it is not explicitly defined.
• A constructor cannot be abstract or static or final.
Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):