Java – Constructors,Syntax
Following is the syntax of a constructor −class ClassName {
ClassName() {
}
}
allows two types of constructors namely −
- No argument Constructors
- Parameterized Constructors
Constructors,No argument Constructors
Constructors,As the call specifies the no argument constructors of Java does not receive any parameters as a substitute, using those constructors the example variables of a technique might be initialized with fixed values for all items.Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
You would call constructor to initialize objects as follows
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
This would produce the following result
100 100
Constructors,Parameterized Constructors
-Constructors,As the call specifies the no argument constructors of Java does not receive any parameters as a substitute, using those constructors the example variables of a technique might be initialized with fixed values for all items.Example
Here is a simple example that uses a constructor −// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
Constructors,This would produce the following result −
10 20