Example of super keyword in java
public class super1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
java obj = new java();
obj.display();
}
}
class cpp
{
int price=300;
}
class java extends cpp
{
int price = 600;
void display()
{
System.out.println("Price of java Book = "+price);
System.out.println("Price of cpp book = "+super.price);
}
}
//****************************************************
output:-
Price of java Book = 600
Price of cpp book = 300
Explanation:- in derived class java, we have used super keyword in display() method.
in this method when first line will execute , it will invoke price variable from java class,
and when second line will execute, it will invoke price variable from class cpp because we have used
super.price
so it will invoke price from immediate parent class i.e. from class cpp
public static void main(String[] args) {
// TODO Auto-generated method stub
java obj = new java();
obj.display();
}
}
class cpp
{
int price=300;
}
class java extends cpp
{
int price = 600;
void display()
{
System.out.println("Price of java Book = "+price);
System.out.println("Price of cpp book = "+super.price);
}
}
//****************************************************
output:-
Price of java Book = 600
Price of cpp book = 300
Explanation:- in derived class java, we have used super keyword in display() method.
in this method when first line will execute , it will invoke price variable from java class,
and when second line will execute, it will invoke price variable from class cpp because we have used
super.price
so it will invoke price from immediate parent class i.e. from class cpp
Comments
Post a Comment