Tuesday, March 3, 2009

java super-java this

super:
super is a keyword which is used to refer the super class from a sub class .It means super can refer the super class instance variables ,super class constructors and also super class methods(instance ,static).super keyword never use in static area like static methods,static blocks.....Because instance variables,constructors ,instance methods these things we will get when the object is created then only we will get.
Example code super:

class One
{
int i;
One()
{
System.out.println("no arg constructor");
}

One(int i)
{
this.i=i;
}
void show()
{
System.out.println("super class method"+i);
}
}
class Two extends One
{
int i;
Two()
{
super();
}
Two(int x,int y)
{
super(x); //calling super class constructor

i=y;
}
void show()
{
System.out.println("sub class method");
super.show(); // calling super class method
System.out.println("super class variable"+super.i); //get super class variable
}
}
class Const
{
public static void main(String arg[])
{
Two t1=new Two();
Two t=new Two(100,200);
t.show();
}
}

this:
this is used to call the present class parameter constructor,present class methods(instance,static),present class instance variables.this keyword never use in static area like static methods,static blocks.....Because instance variables,constructors ,instance methods these things we will get when the object is created then only we will get.
Example code this:

class Sample
{
int n;
Sample()
{
this(100); // this class constructor
this.display(); // this class method
}
Sample(int n)
{
this.n=n; // this class instance variable

}
void display(){
System.out.println("n="+n);
}
}
class ThisDemo
{
public static void main(String arg[])
{
Sample s=new Sample();
}
}

2 comments:

Bruce Clark said...

Thanks, I found your article very useful and interesting for me. Its very cool that in out modern age people still share helpful information with each others. Thats why I wanna suggest you this amazing site with best tutorials about java static method https://explainjava.com/java-static-methods/ in the whole internet!

sriram said...

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.

software testing course in chennai

Post a Comment