Key and important note on constructors
- Block of code executed whenever an object is created
- Constructor does not return any values
- Name of the Constructor should be the class name.
- Compiler will call default/implicit constructor(java- library-if not defined any constructor block).
- Constructor will be called whenever an object is created.
- In real-time Constructor is used to define variables or to initiate properties
sample code for constructor:
public class constructorDemo {
public constructorDemo() {
System.out.println("i am in the constructor");
}
public void getData() {
System.out.println("i am the method");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
constructorDemo obj = new constructorDemo();
// obj is created to call constructor (constructorDemo)
}
}
Parameterized constructor
public class constructorDemo {
public constructorDemo() {
System.out.println("i am in the constructor");
}
public constructorDemo(int a, int b) {
System.out.println("i am in the parametrized constructor");
int c = a + b;
System.out.println(c);
}
public constructorDemo(String str) {
System.out.println(str);
}
public void getData() {
System.out.println("i am the method");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
constructorDemo obj = new constructorDemo(4, 5);
constructorDemo obj1 = new constructorDemo("Hello");
// obj is created to call constructor (constructorDemo)
}
}
No comments:
Post a Comment