Constructor chaining example program in same class using this keyword.
Constructor chaining example program in same class using this and super keywords.
- package instanceofjava;
- class ConstructorChaining{
- int a,b
- ConstructorChaining(){
- this(1,2);
- System.out.println("Default constructor");
- }
- ConstructorChaining(int x , int y){
- this(1,2,3);
- a=x;
- b=y;
- System.out.println("Two argument constructor");
- }
- ConstructorChaining(int a , int b,int c){
- System.out.println("Three argument constructor")
- }
- public static void main(String[] args){
- ConstructorChaining obj=new ConstructorChaining();
- System.out.println(obj.a);
- System.out.println(obj.b);
- }
- }
Output:
- Three argument constructor
- Two argument constructor
- Default argument constructor
- 1
- 2
Constructor chaining example program in same class using this and super keywords.
- package instanceofjava;
- class SuperClass{
- SuperClass(){
- this(1);
- System.out.println("Super Class no-argument constructor");
- }
- SuperClass(int x ){
- this(1,"constructor chaining");
- System.out.println("Super class one -argument constructor(int)");
- }
- SuperClass(int x , String str){
- System.out.println("Super class two-argument constructor(int, String)");
- }
- }
- package instanceofjava;
- class SubClass extends SuperClass{
- SubClass(){
- this(1);
- System.out.println("Sub Class no-argument constructor");
- }
- SubClass(int x ){
- this("Constructor chaining");
- System.out.println("Sub class integer argument constructor");
- }
- ConstructorChaining(String str){
- //here by default super() call will be there so it will call super class constructor
- System.out.println("Sub class String argument constructor");
- }
- public static void main(String[] args){
- SubClass obj=new SubClass();
- }
- }
Output:
- Super class two-argument constructor(int, String)
- Super class one -argument constructor(int)
- Super Class no-argument constructor
- Sub class String argument constructor
- Sub class String argument constructor
- Sub class integer argument constructor
In your SubClass Constructor of String it the constructor name is wrong. Kindly correct it.
ReplyDelete