The use of "this " keyword in Java
Inheritance in Java is a mechanism that is used to pass properties and behaviours of a parent object to child objects.
In inheritance, you can create new classes that are built using existing classes.Inheritance represents IS_A relationship i.e parent-child relationship.
A child class can use methods and fields of the parent class.
In inheritance, you can create new classes that are built using existing classes.Inheritance represents IS_A relationship i.e parent-child relationship.
A child class can use methods and fields of the parent class.
Importance of Inheritance in Java
1.For method overriding .
2.Code reuse.
Inheritance Syntax
extends keyword is used to make a child class from the parent.
public class JButtonListener extends JFrame {
}
Java Inheritance Example
Parent Class
public class Students {
int id;
String name;
String class_name;
String school_name="Ikuu Boys";
}
Child Classpublic class FormOneStudents extends Students {
String form_name="Form one West";
public static void main(String args[])
{
FormOneStudents f=new FormOneStudents();
System.out.println("School name " +f.school_name);
System.out.println("Form name " +f.form_name);
}
}
Types of Inheritance in Java
There are 3 types of inheritance in java
- Single
- Multilevel
- hierarchical.
- 1.Example of a single Inheritance java example.
public class Animal {
void eat()
{
System.out.println("All Animals eat");
}
}
Child Class public class Cat extends Animal
{
void Meow()
{
System.out.println("Cats meows");
}
public static void main(String args[])
{
Cat c= new Cat();
c.Meow();
c.eat();
}}
- 2.Multilevel Java Example
public class Animal {
void eat()
{
System.out.println("All Animals eat");
}
}
public class Cat extends Animal
{
void Meow()
{
System.out.println("Cats meows");
}
}
public class BabyCat extends Cat{
public static void main(String args[])
{
BabyCat c= new BabyCat();
c.Meow();
c.eat();
}
}
public class Animal {
void eat()
{
System.out.println("All Animals eat");
}
}
public class Cat extends Animal
{
void Meow()
{
System.out.println("Cats meows");
}
}
public class BabyCat extends Cat{
public static void main(String args[])
{
BabyCat c= new BabyCat();
c.Meow();
c.eat();
}
}
- 3.Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}