Inheritance in java

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.


We are creating a class name animal and we are extending the animal class in dog. Basically we are creating a inheritance of dog.



package com.ritesh;
class animal{
String name;
int age;

//getter and setter in age
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age;
}
//getter and setter with name
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}

}
class dog extends animal{

public void bark(){
System.out.println("Dog is barking");
}
public void bite(){
System.out.println("Dog can bite");
}

}

public class inheritance {
public static void main(String[] args) {
// calling the value of animal class..
animal a1=new animal();
a1.setAge(44);
a1.setName("Munna");
System.out.println(a1.getAge());
System.out.println(a1.getName());

//calling the value of dog class
dog a2=new dog(); //we can also access the parameter animal class.
a2.setAge(22);
a2.setName("Lussy");
System.out.println(a2.getAge());
System.out.println(a2.getName());
a2.bark();
a2.bite();
}

}


 Practicing inheritance by the example of class name phone and extends the phone class in smartphone.

Basically we are not making the phone with is already made by other we are updating the phone into smartphone.


package com.ritesh;
class phone1{
public void ring(){
System.out.println("The phone is ringing");
}
void call(){
System.out.println("Phone is calling ram");
}
public void sms(){
System.out.println("Phone is sending txt to hari");
}

static class smart_phone extends phone1{
public void play_song(){
System.out.println("Playing a song");
}
public int add(int a, int b){
return a+b;
}
public void youtube(){
System.out.println("Playing youtube");
}
}


}

public class phone {
public static void main(String[] args) {
phone1.smart_phone ph=new phone1.smart_phone();
ph.ring();
ph.call();
ph.sms();
ph.play_song();
System.out.println( ph.add(3,6));
ph.youtube();
}
}

 

Comments