Open In App

Java – Inner Class vs Sub Class

Last Updated : 31 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Inner Class

In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types:

  • Nested Inner Class
  • Method Local Inner Class
  • Anonymous Inner Class

Generally, it makes code slightly complicated but, it is very useful with abstract window toolkit and AWT(GUI) event handling.

Example:

Java




public class Outer { // outer class
    void showData()
    { // method inside outer class
        ---
    }
    public class Inner { // inner class inside outer class
    }
}


Sub Class

In Java, a subclass is a class that derives/inherited from another class. A subclass inherits everything (like behavior, state of the class, etc. ) from its ancestor classes. For a better understanding of it, we just need to know about the superclass. The superclass is an immediate ancestor of the sub-class. As a subclass has the property of inheriting the properties of an ancestor, hence, it can modify or override the methods of the superclass. For creating a subclass from any other class, we need to use extends clause in the class declaration. 

Example :

Java




// super class
public class Mahindra {
    public Mahindra()
    {
        System.out.println("I am super class");
    }
}
  
// sub class
public class Scorpio extends Mahindra {
    public Scorpio()
    {
        System.out.println("I am sub class");
    }
}


Difference Table

The difference between the Inner class and sub-class are listed below:

Inner Class

Sub Class

It is a class that is nested within another class. It is a class that inherits from another class.
It can be accessed with the reference of the outer class. No reference is required. It can be accessed directly without any reference to any class.
It is useful in performing encapsulation properties of OOPs and event handling in AWT(GUI). It is beneficial in performing the inheritance property of object-oriented programming (OOPs).
It is used when the “has-a” relationship with its outer class is defined. It is used when the “is-a” relationship is defined with its parent class.
It contains methods as per the requirement. It must include the methods which are present in the parent class. Also, it can include any other methods too as per the need.
It is always present in the same file where the outer class is present. It may or may not be available in the same file/package as its parent class.
It cannot define any static methods inside it. It contains all types of methods either static or non-static.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads