MainMenu

Home Core Java Overview Maven Tutorials

Sunday, 15 January 2017

Constructor, Super & this keyword in java



For Video Tutorial : Move on Youtube Channel



Note : Select the playlist as per your need & move with number sequence


Constructor in Java with example


For Video : CLICK HERE


A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Constructor Example :


public class cons
{
cons(int a, int b)
{
System.out.println("your sum is :" +(a+b));
}
public static void main(String args[])
{
cons obj = new cons(3,5);
}
}
Output : your sum is :8

For Video : CLICK HERE



Super Keyword



The super keyword in java is a reference variable that is used to refer immediate parent class object.
If parent & child class both have same variable and parent class is inherited by child class(by extends) then only child class variable will be accessible and to access the parent class variable we have to use Super keyword.

Super Keyword Example in Java:


class parent
{
int x =20;
}
public class child extends parent
{
int x = 10;
public void sub()
{
System.out.println("value of x with super keyword : " +super.x);
System.out.println("value of x without super keyword : " +x);
}
public static void main(String args[])
{
child obj = new child();
obj.sub();
}
}
Output :
value of x with super keyword : 20
value of x without super keyword : 10

This Keyword in Java:


This keyword is used to resolve the ambiguity issue between the instance variable and the parameter.

This Keyword Example in Java:


public class cons
{
int x , y, z;
public cons(int x , int t, int z)
{
x = x;
y=t;
this.z = z;
}
public static void main(String args[])
{
cons obj = new cons(3, 50, 40);
System.out.println("i am confuse who is x :" +obj.x);
System.out.println("i know that your are global variable :" +obj.y);
System.out.println("Thanks this, now i know you z :" +obj.z);
}
}
Output :
i am confuse who is x :0
i know that your are global variable :50
Thanks this, now i know you z :40

Tags : What is constructor in java?, what is this keyword in java?, what is super keyword in java


No comments:

Post a Comment