super() and this()

Total Post:113

Points:791
Java 
 221  View(s)
Ratings:
Rate this:

What is  the difference between super() and this() ? explain with example. 

  1. Post:140

    Points:984
    Re: super() and this()

    Difference between super() and this() in java:

    super() as well as this() both are used to make constructor calls. super() is used to call Base class’s constructor coz they are Parent’s class while this() is used to call current class’s constructor.We can use super() as well this() only once inside constructor.  

    Example super() : 

     
    class Parent { 
        Parent()
        { System.out.println("mindstick " + " arg constructor"); }
      }
    class Child extends Parent {
        Child()
        {
            super();
            System.out.println("software" +
                            "Parent class no arg const");     }
        public static void main(String[] args)
        {
            new Child();
            System.out.println("Inside Main");
        }
    }

    Example this() :

    class MM { 
        MM()
        { this(10);
            System.out.println("Flow comes back from " + "MM class's 1 arg const");
        }
        MM(int a)
        {
            System.out.println("MM class's 1 arg const");
        }
        public static void main(String[] args)
        {
            new MM();
            System.out.println("Inside Main");
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!