super keyword in java

What is the use of Super keyword

  • A super keyword used to refer super class property from sub class
  • It is used in non static context only

How to refer Super class Property from sub class ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package keyword;
 
class demo1
 {
   int k=10;
 } 
 
//creating sub class
class Sample extends demo1
  {
    int k=12;
    void disp()
     {
       System.out.println(this.k);//referring current class property
       System.out.println(super.k);//referring super class property from subclass
     }
}
 
public class SuperKeyword
  {
public static void main(String[] args)
  {
    System.out.println("********************");
    Sample obj1=new Sample();
    obj1.disp();
    System.out.println("*********************");
  }
}
OUTPUT:
********************
12
10
*********************

this keyword in java

What is this keyword in java ?
  • This keyword is use to refer current class object
  • This keyword contain address of object
  •  It is only used in non static context
  •  Whenever local variable and class variable name is same, we can differentiate data member from local variable using this keyword
Example of this Keyword
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
package keyword;
 
class Sample3
{
	//data member of class
	int k=10;
	double d=2.4;
 
	Sample3(double d)
	{
		this.d=d;
 
	}
 
	void test()
	{
		int k=12; //local variable
 
		System.out.println("running test method");
 
		System.out.println("k value "+this.k);
 
		System.out.println("local variable k value: "+k);
 
		System.out.println("address of current class object");
 
		System.out.println(this);
 
	}
 
}
 
 
public class Thiskeyword
{
	public static void main(String[] args)
 
	{
		System.out.println("************************");
 
		Sample3 obj1=new Sample3(2.55555555);
		System.out.println("d value: "+obj1.d);
		obj1.test();
		System.out.println("************************");
	}	
}
 
output:
 
************************
d value: 2.55555555
running test method
k value 10
local variable k value: 12
adress of current class object
keyword.Sample3@15db9742
************************