Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

Jul 5, 2020

Inheritance in JAVA | Java Language | Coding Winds

INHERITANCE IN JAVA (Superclasses/ Subclasses)

So as we talked about polymorphism in method overloading, now we are about to talk about inheritance as well which is one of the another pillar in OOPs. So in this topic we will learn how to extend a class or in simple words how to use the elements of one class into another by making them sort of one. So before looking forward to the syntax of extending a class let’s first know about the term ‘subclasses’ and ‘superclasses’. So subclasses are the ones in which we tend reuse the properties of an older or a base class, and superclasses are those base classes whose properties we use in the subclasses. So let’s look at the syntax of how to actually derive an new class from on old one.

Syntax:

class subclassName extends superclassName{

}

Now inside the method body above we can use the variables and methods of the base class (super class) and declare the new ones too. So let’s see an example of how to implement this in an actual program

import java.util.*;

class Add{

     static int a,b,c;

 static void sum() {

               c= a+b;

          System.out.println(c);

         }

 }

 

public class Solution extends Add {

     public static void main(String[] args) {

           Scanner sc = new Scanner(System.in);

           a=2;

           b=5;

           sum();  //Output: 7

     }

     }

Note that the keyword ‘static’ is used while declaring the variables of the parent class because (as discussed earlier) to use the variables and methods for the same class (but not in the same main method), and when we extend a base class the compiler treats the new subclass and superclass as one.

Now let’s see how can we use multilevel inheritance in java i.e., extending a superclass and then again extending the subclass (or using this subclass as a superclass for the next class).

import java.util.*;

 

class Add{

     static int a,b,c;

 static void sum() {

               c= a+b;

          System.out.println(c);

         }

 }

class Subtract extends Add{

     static void minus() {

         c=a-b;

         if(c<0) {

              c=-c;

         }

         System.out.println(c);

     }

}

 

public class Solution extends Subtract {

     public static void main(String[] args) {

           Scanner sc = new Scanner(System.in);

           a=2;

           b=5;

           sum();       //Output: 7

           minus();      //Output:3

     }

     }

Hope you are clear on this  topic do read our more articles on JAVA LANGUAGE.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


This article is SUBMITTED By : Pranjal Rai


Do subscribe to our daily blog update by clicking here.


Thank You!