Thursday, December 26, 2024
Google search engine
HomeLanguagesJavaDifferent Types of Classes in Java with Examples

Different Types of Classes in Java with Examples

A class is a user-defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:  

  • Modifiers: A class can be public or has default access
  • class keyword: class keyword is used to create a class.
  • Class name: The name should begin with an initial letter (capitalized by convention).
  • Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  • Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  • Body: The class body surrounded by braces, { }.

We can define class members and functions inside the class. Different types of classes:

  1. Static Class
  2. Final Class
  3. Abstract Class
  4. Concrete Class
  5. Singleton Class
  6. POJO Class
  7. Inner Class

1. Static Class

We can declare a class as static if and only if it is a nested class. We can declare an inner class with the static modifier, such types of inner classes are called static nested classes. In the case of normal or regular class without the existing outer class object, there is no chance of existing inner class object i.e inner class object is strongly associated with an outer class object. In the case of static nested classes, there may be a chance of declaring the nested class object without an outer class object. 

Note:

If we want to declare a nested class object from outside of the outer class then we can create as follows

Syntax: 

Outerclassname.innerclassname objectvariable= new Outerclassname.innerclass name();

Example: 

Test.Nested n= new Test.Nested();

Hence it is said that there may be a chance of existing nested class objects without existing outer class objects. In normal or regular inner classes we can’t declare any static members, but in static nested classes we can declare static members including the main method, so, we can invoke static nested class directly from the command prompt. 

Properties of the static class:

  1. static class objects cannot be created.
  2. static class can only have static members.
  3. static class cannot access members (non-static) of the outer class.

Example:

Java




class Outer {
    static class Nested {
        public static void main(String arg[])
        {
            System.out.println(
                "static method class main method");
        }
    }
  
    public static void main(String arg[])
    {
        System.out.println("Outer class main method");
    }
}


Output:

Output

2. Final Class

The class can be declared as final by using the keyword ‘final’. If a class is declared as final we can’t extend the functionality of that class i.e we can’t create a child class for that class, i.e inheritance is not possible for final classes. Every method present inside the ultimate class is usually final by default, but every variable present inside the ultimate class needn’t be final. If we create the final class we cannot achieve inheritance. If we create a final method we cannot achieve polymorphism, but we can obtain security no one can change our code’s unique implementation, but the main disadvantage of the final keyword is we are missing the benefits of inheritance and polymorphism. 

Note: If there is no specific requirement it is not recommended to use the final keyword.

Example:

Java




final class Sound {
    static int number = 10;
    void message()
    {
        number = 777;
        System.out.println(number);
    }
}
  
class Animal extends Sound {
    static int number = 9;
    void message()
    {
        super.number = 888;
        System.out.println(super.number);
    }
  
    public static void main(String arg[])
    {
        Animal a = new Animal();
        a.message();
    }
}


Output:

Output

3. Abstract Class

We can declare a class as abstract by using the keyword ‘abstract’. For any java class if we are not allowed to create an object such type of class, we should declare with the abstract modifier, i.e for abstract classes instantiation is not possible. If a class contains at least one abstract method then compulsory we should declare a class as abstract otherwise we get a compilation error. Reason: If a class contains at least one abstract method then implementation is not complete and hence it is not recommended to create an object. If we need to restrict object instantiation compulsory we need to declare the class as abstract. A class containing either zero or more abstract methods can be an abstract class if we don’t want any instantiation. Example: HttpServletClass is abstract but it doesn’t contain any abstract methods.

If we are extending abstract class then for every and each abstract method of parent class we should always provide implementation, otherwise, we’ve to declare child class as abstract. In this case, the next-level child class is responsible to provide the implementation.

Example:

Java




abstract class AbstractClass {
    public abstract void add(int a, int b);
    public abstract void sub(int a, int b);
    public void mul(int a, int b)
    {
        System.out.println("Multiplication of a and b is"
                           + " " + (a * b));
    }
}
class Geek extends AbstractClass {
    public void add(int a, int b)
    {
        System.out.println("Sum of a and b is"
                           + " " + (a + b));
    }
    public void sub(int a, int b)
    {
        System.out.println("Difference of a and b is"
                           + " " + (a - b));
    }
    public static void main(String[] args)
    {
        int a = 6;
        int b = 5;
        Geek g = new Geek();
        g.add(a, b);
        g.sub(a, b);
        g.mul(a, b);
    }
}


Output:

Output

4. Concrete Class

A concrete class is nothing but a normal or regular class in java. A concrete class is a class that extends another class or implements an interface. In short, we can say that any class which is not abstract is said to be a concrete class. We can directly create an object for the concrete class.

Note: A class is said to be a concrete class if there is an implementation for each and every method.

Example:

Java




public class ConcreteClass
{
    // method of the concreted class
    static int addition(int a, int b) { return a + b; }
  
    public static void main(String args[])
    {
        // method calling
        int p = addition(5, 9);
        System.out.println("The result of a and b is: "
                           + p);
    }
}


Output:

Output

5. Singleton Class

For any java class if we are allowed to make just one object such sort of class is claimed to be a singleton class.

Example: Runtime, BusinessDelegate, ServiceLocator

Advantages:

  • If several people have the same requirement then it’s not recommended to make a separate object for each requirement, we’ve to make just one object so that we can reuse an equivalent object for each similar requirement, in order that performance and memory utilization are going to be improved.
  • This is often the central idea of singleton classes.

We can also create our own singleton classes, for that we’d like to possess  

  • Private constructor
  • Private static variable and the public factory method

Example:

Java




class Test {
  
    private static Test t = null;
    public String s;
  
    private Test() throws Exception
    {
        s = "I am example of singletonclass";
    }
  
    public static Test getTest()
    {
        if (t == null) {
            try {
                t = new Test();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return t;
    }
  
    public String gets() { return s; }
    public void sets(String s) { this.s = s; }
}
  
class Geeks {
  
    public static void main(String arg[])
    {
        Test t1 = Test.getTest();
        Test t2 = Test.getTest();
        Test t3 = Test.getTest();
        t1.getTest();
        System.out.println("Hashcode of t1 is "
                           + t1.hashCode());
        System.out.println("Hashcode of t2 is "
                           + t2.hashCode());
        System.out.println("Hashcode of t3 is "
                           + t3.hashCode());
    }
}


Output:

Output

6. POJO Class

POJO stands for Plain Old Java Object. If we write a category, then it got to follow some rules referred to as POJO rules. it’s wont to java to extend readability and reusability. It provides Encapsulation.

Properties of POJO class:

  1. class must be declared as public
  2. properties/variables must be declared as private
  3. Must have a public default constructor
  4. May or might not have argument constructor
  5. Every property should have a public getter and setter methods
  6. It cannot contain pre-specified annotations.

Example:

Java




class Pojoclass {
  
    private String name = "Geeks for Geeks";
    public void setName(String name) { this.name = name; }
    public String getName() { return name; }
}
  
public class PojoExample
{
    public static void main(String args[])
    {
        Pojoclass obj = new Pojoclass();
        System.out.println("The name of an student is "
                           + obj.getName());
    }
}


Output:

Output

7. Inner Class

Sometimes we can declare a class inside another class such types of classes is called inner classes. Inner classes concept is introduced to fix GUI bugs as a part of event handling but because of powerful features and benefits of inner classes slowly programmers are started using in regular coding also. Without existing one type of object there is no chance of executing another type of object then we should go for inner classes.

Example: University consists of several departments, without existing university there is no chance of existing department, hence we have to declare department class inside university class.

Class University{
  // code
    Class Department{
        // code
    }
}

The relation between outer class and inner class is said to be a Has-A relationship. Based on the position of declaration and behavior all inner classes are divided into four types.

  • Normal or Regular classes
  • Method local Inner classes
  • Anonymous Inner classes
  • Static nested classes

Normal and Regular Inner classes:

If we are declaring any named class directly inside a class without the static modifier, such a type of inner class is called Normal or Regular inner class.

Example:

Java




class Outer1 {
    class Inner {
        public void m1()
        {
            System.out.println("Inner class method");
        }
    }
  
    public static void main(String arg[])
    {
        Outer1 o = new Outer1();
        Outer1.Inner i = o.new Inner();
        i.m1();
    }
}


Output:

Output

Nesting of Inner Classes:

Inside inner classes, we can declare another inner class i.e nesting of inner classes is possible.

Example:

Java




class A {
    class B {
        class C {
            public void m1()
            {
                System.out.println(
                    "Innermost class method");
            }
        }
    }
}
  
class Test {
    public static void main(String arg[])
    {
        A a = new A();
        A.B b = a.new B();
        A.B.C c = b.new C();
        c.m1();
    }
}


Output:

Output

Method local Inner classes:

Sometimes we can declare a class inside a method, such types of inner classes are called method local inner classes. The main purpose of the method local inner class is to define method-specific repeated functionality. Method local inner classes are best suitable to meet nested class requirements. We can access the method, local inner classes, only within the method where we declare, outside of the method we can’t access and use of its less scope method local inner classes are most rarely used type of inner classes.

Note: The only applicable modifier for method local inner classes are final, abstract, Strictfp. If we are trying to apply any other modifier then we will get a compilation error.

Example:

Java




class Outer2 {
    public void m1()
    {
        class Inner {
            public void sum(int x, int y)
            {
                System.out.println("The sum"
                                   + " " + (x + y));
            }
        }
  
        Inner i = new Inner();
        i.sum(10, 20);
        i.sum(100, 200);
        i.sum(1000, 2000);
    }
  
    public static void main(String arg[])
    {
        Outer2 t = new Outer2();
        t.m1();
    }
}


Output:

Output

Note: We can declare the method local inner class inside both instance and static method. If we declare the inner class inside the instance method then from that method local inner class, we can access both static and non-static members of the outer class directly.

Anonymous Inner classes:

Sometimes we declare inner classes without a name such types of inner classes are called anonymous inner classes. The main purpose of anonymous inner classes is just for instant use. Based on declaration and behavior there are three types of anonymous inner classes

  1. Anonymous inner class that extends a class
  2. Anonymous inner class that implements an interface
  3. Anonymous inner class that defines the inside argument

Example:

Java




class ThreadDemo {
    public static void main(String arg[])
    {
        new Thread(
            new Runnable()
            {
                public void run()
                {
                    for (int i = 0; i <= 5; i++)
                    {
                        System.out.println("Child Thread");
                    }
                }
            })
            .start();
  
        for (int i = 0; i <= 5; i++)
        {
            System.out.println("Main thread");
        }
    }
}


Output:

Output

Static Nested classes:

We can declare inner classes with static modifiers such types of inner classes are called static nested classes.

Example:

Java




class StaticNested1 {
  
    private static String str = "Geeks for Geeks";
  
    static class Nested {
        public void m1() { System.out.println(str); }
    }
  
    public static void main(String args[])
    {
        StaticNested1.Nested obj
            = new StaticNested1.Nested();
        obj.m1();
    }
}


Output:

Output

RELATED ARTICLES

Most Popular

Recent Comments