Inheritance - Java
Re-using the properties of existing ones are called inheritance or derivation, we have several types of inheritances in object oriented programming they are
- Simple
- Multilevel
- Multiple
- Hyrarchical
- Hybrid
Java doesnot support Multiple and Hybrid Inheritance.
In the terminology of java a class that is inherited is called as super class. The class that does the inheriting is called as sub class. These two are the alternative words for c++ base class and derived class. To inherit a class you simply incorporate the definition of one class into another by using the extends keyword.
WRITE A PROGRAM ON INHERITANCE.
class Abc
{
int a;
public void get()
{
System.out.println(a);
}
}
class Xyz extends Abc
{
int b;
public void put()
{
System.out.println(b);
}
}
class Sample
{
public static void main(String args[])
{
Xyz x=new Xyz();
Abc k=new Abc();
k.a=20;
k.get();
x.b=20;
x.put();
}
}
WRITE A PROGRAM TO FIND THE TOTAL AND AVERAGE MARKS OF A STUDENT.
class Abc
{
int m,p,c;
public void get()
{
m=20;
p=40;
c=80;
}
}
class Stud extends Abc
{
int t,a;
public void put()
{
t=m+p+c;
a=t/3;
}
}
class Sample
{
public static void main(String args[])
{
Stud s=new Stud();
s.get();
s.put();
System.out.println("Total: "+s.t);
System.out.println("Average: "+s.a);
}
}
WRITE A PROGRAM ON CONSTRUCTORS IN SUBCLASS.
class Sum
{
int a;
public void get()
{
System.out.println(a);
}
}
class Xyz extends Sum
{
int k;
Xyz(int x,int y)
{
a=x;
k=y;
}
public void put()
{
System.out.println(a+k);
}
}
class Sample
{
public static void main(String args[])
{
Xyz x=new Xyz(10,20);
x.get();
x.put();
}
}
WRITE A PROGRAM ON CONSTRUCTORS FOR BOTH THE CLASSES.
class Sum
{
Sum()
{
System.out.println("This is super class");
}
}
class Sub extends Sum
{
Sub()
{
System.out.println("Sub Class");
}
}
class Sample
{
public static void main(String args[])
{
Sub s=new Sub();
}
}
WRITE A PROGRAM TO PRINT THE VALUES USING CONSTRUCTORS FOR SUPER CLASS AND SUBCLASS USING SUPER KEY WORD.
class Sum
{
int a,b;
Sum(int x,int y)
{
a=x;
b=y;
}
public int put()
{
return(a*b);
}
}
class Xyz extends Sum
{
Xyz(int x,int y)
{
super(x,y);
}
}
class Sample
{
public static void main(String args[])
{
Xyz x=new Xyz(10,20);
int k=x.put();
System.out.println(k);
}
}
For
More Explanation
&
Online Classes
More Explanation
&
Online Classes
Contact Us:
+919885348743
+919885348743