Java program showing concept of Inheritance
Inheritance is a feature of Object oriented language like JAVA where child class acquires properties and methods of it's parent class.
package inheritance;
public class SuperDemo
{
public void showname()
{
System.out.println("This is my SuperClass");
}
}
public class DemoClass extends SuperDemo
{
public void display()
{
System.out.println("This is subclass");
}
public static void main(String[] args)
{
DemoClass demo=new DemoClass();
demo.showname();
demo.display();
}
}
public class SuperDemo
{
public void showname()
{
System.out.println("This is my SuperClass");
}
}
public class DemoClass extends SuperDemo
{
public void display()
{
System.out.println("This is subclass");
}
public static void main(String[] args)
{
DemoClass demo=new DemoClass();
demo.showname();
demo.display();
}
}
Output
This is my SuperClass
This is subclass
This is subclass
Explanation
Using super
package inheritance;
public class Expensive
{
int tv_price=20000;
public void showExpense()
{
System.out.println("The price of tv is " + tv_price);
}
}
public class NonExpensive extends Expensive
{
int cooler=5000;
public void showExpense()
{
System.out.println("The price of cooler is " + cooler);
}
public void getExpense()
{
NonExpensive nonex=new NonExpensive();
//call subclass method
nonex.showExpense();
//call superclass method
super.showExpense();
//get the value of tv in superclass
int k=super.tv_price;
System.out.println(k);
}
public static void main(String[] args)
{
NonExpensive ex=new NonExpensive();
ex.getExpense();
}
}
Output
public class Expensive
{
int tv_price=20000;
public void showExpense()
{
System.out.println("The price of tv is " + tv_price);
}
}
public class NonExpensive extends Expensive
{
int cooler=5000;
public void showExpense()
{
System.out.println("The price of cooler is " + cooler);
}
public void getExpense()
{
NonExpensive nonex=new NonExpensive();
nonex.showExpense();
super.showExpense();
int k=super.tv_price;
System.out.println(k);
}
public static void main(String[] args)
{
NonExpensive ex=new NonExpensive();
ex.getExpense();
}
}
The price of cooler is 5000
The price of tv is 20000
20000
Explanation
Java program showing concept of Inheritance
Reviewed by LanguageExpert
on
August 18, 2018
Rating:
No comments