Unit 3.1-Inheritance
Unit 3.1-Inheritance
Inheritance:
Syntax of Inheritance:
The extends keyword indicates that you are making a new class that
derives from an existing class.
The meaning of "extends" is to increase the functionality.
class Vehicle.
{ ......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
We can use super keyword to access the data member or field of parent class. It
is used if parent class and child class have same fields.
class Animal
{
String type="mammal";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println("Dog color:"+color);
System.out.println("dog type: "+super.type);
}
}
class testsuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
2.super can be used to invoke parent class
method
The super keyword can also be
used to invoke parent class method.
It should be used if subclass
contains the same method as parent
class. In other words, it is used if
method is overridden.
Examples:
class Animal
{
void eat()
{
System.out.println("Animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("Dog is eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
}
}
class testsuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
3)super is used to invoke parent class constructor.
Example:
class applicant
{
String name,city;
applicant(String n,String c)
{
name=n;
city=c;
}
void dispapp()
{
System.out.println("Name: "+name+"\nCity: "+city);
}
}
class employee extends applicant
{
int empid,deptid;
employee(String n,String c,int e,int d)
{
super(n,c);
empid=e;
deptid=d;
}
void dispemp()
{
System.out.println("Emp Id: "+empid);
System.out.println("Dept Id: "+deptid+"\n");
}
}
class testsuper3
{
public static void main(String args[])
{
employee e1=new employee("Rahul","Nashik",101,111);
e1.dispapp();
e1.dispemp();
employee e2=new employee("Rohan","Pune",102,112);
e2.dispapp();
e2.dispemp();
}
}