Single inheritance is the most simple form among five types of inheritance. It requires one superclass and one subclass.
Examples: Dog IS-A Canine, Student IS-A Person, Mobile Phone IS-A Electronics
We adopt Dog and Canine as single inheritance example. Dog is one kind of Canine. They share common attributes like color, size. For simplicity we don't use abstraction but the concept is the same. We create Canine class with instance variables color and size as well as instance methods. Then Dog inherits from Canine and gets all its instance variables and methods. Later we create a Dog object and set its color and size. That is single inheritance.
We adopt Dog and Canine as single inheritance example. Dog is one kind of Canine. They share common attributes like color, size. For simplicity we don't use abstraction but the concept is the same. We create Canine class with instance variables color and size as well as instance methods. Then Dog inherits from Canine and gets all its instance variables and methods. Later we create a Dog object and set its color and size. That is single inheritance.
class Canine
{
String color;
int size;
public int getSize()
{ return size; }
public String getColor()
{ return color; }
public void setSize(int s)
{ size = s; }
public void setColor(String c)
{ color = c; }
}
class Dog extends Canine { }
public class SingleInheritanceTest
{
public static void main (String args[])
{
Dog d1 = new Dog();
d1.setColor("brown");
d1.setSize(30);
System.out.println("Dog color: "+ d1.getColor());
System.out.println("Dog size: "+ d1.getSize());
}
}
Results:
Dog color: brown
Dog size: 30
String color;
int size;
public int getSize()
{ return size; }
public String getColor()
{ return color; }
public void setSize(int s)
{ size = s; }
public void setColor(String c)
{ color = c; }
}
class Dog extends Canine { }
public class SingleInheritanceTest
{
public static void main (String args[])
{
Dog d1 = new Dog();
d1.setColor("brown");
d1.setSize(30);
System.out.println("Dog color: "+ d1.getColor());
System.out.println("Dog size: "+ d1.getSize());
}
}
Results:
Dog color: brown
Dog size: 30
No comments:
Post a Comment