What is Constructor in Java?
- A constructor is a member method
- Should have same name as class name
- It will never return anything
- It will use to allocate memory.
class ConstructorExample {
int x;
String y;
public ConstructorExample() {
//constructor can be used to initialize default values for variables
x = 5;
y = "Hello World";
}
//parameterize Constructor
public ConstructorExample(int k, String str) {
//constructor can be used to initialize default values for variables
x = k;
y = str;
}
}
class inside a class(Inner Class)
class Outer {
int i;
class Inner {
public void show() {
System.out.println("Method inside inner class");
}
}
static class InnerStatic {
public void show() {
System.out.println("Method inside static inner class");
}
}
}
public class InnerDemo {
public static void main(String a[]) {
Outer outerObj = new Outer();
// access Inner class method
Outer.Inner innerObj= outerObj.new Inner();
innerObj.show();
Outer.InnerStatic innerStaticObj = new Outer.InnerStatic();
innerStaticObj.show();
}
}
// OUTPUT:
// Method inside inner class
// Method inside static inner class
Comments
Post a Comment