DEV Community

R.Shobika CSE
R.Shobika CSE

Posted on

INHERITANCE IN JAVA

INHERITANCE:

  • Inheritance in Java is a core OOP concept that allows a class to acquire properties and behaviors from another class

  • A subclass can reuse the fields and methods of the parent class without rewriting the code

  • A subclass can add its own fields and methods or modify existing ones to extend functionality.

public class Animal { ----->super class/ parent class

    public void sound() {
        System.out.println("animal sound");
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();
    }
}

class Dog extends Animal { ---->sub class/child class

}
Enter fullscreen mode Exit fullscreen mode

Output:
animal sound

what happened if we print object ?

if we print the object means its give the hash code

class Student{
public void name(){
System.out.println("abc");
}
}
public static void main (String[] args){
Student s = new Student();
System.out.println(s)
}
Enter fullscreen mode Exit fullscreen mode

output:
Student@5e91993f

if we print the object means it will show the hashcode value because each class have the toString() method in java the inbuild function have the own toString() method in some in bulid function does not have so that time that method call the their immediate parent .

Method overriding:

  • Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its parent class

  • It is one of the key features of runtime polymorphism in object-oriented programming.

Same method name same no of arguments same return type is called method overriding

public class Student{
String name ="abc";
public static void main(String[] args){
Student s = new Student();
System.out.println(s);
}
public String toString(){
return name;

}
}
Enter fullscreen mode Exit fullscreen mode

output:
abc

Here the object s is search for toString() method for printing so the object s is going to check the object s class "Student" it check whether there is a toString method or not if method is in the Student class means it need not to go for parent class if method not in the class means it go and check the object class , so we can write the same method same argument in the child class also that is called a method overriding

Top comments (0)