Types of Classes in Java

by | Jan 6, 2023 | Java

Home » Java » Types of Classes in Java

Introduction

Classes can be treated as store houses of objects in the sense that classes are called blueprints of objects. It is from here that individual objects are created. In Java, we can create a class using the keyword class. It is used to declare a class which is then followed by code that goes inside the body f the class. A class generally contains several methods and functions. To create a Java program, it is mandatory to create classes. Classes are often referred to as user-defined data types because an object-oriented paradigm allows us to model real-world objects. This article will focus on the various types of classes that are available in Java.

Types of Classes

Java allows developers to create seven different types of classes, and the list is growing in size with every new update of Java. The current types are:

  • Static Class
  • Final Class
  • Abstract Class
  • Concrete Class
  • Singleton Class
  • POJO Class
  • Inner Class

Static Class

In Java, to manage objects in the memory, the keyword static is used. An object that is defined as static belongs to the class itself and not the instance of a class (instance object). A class can only be made static if the class is a nested class. Alternatively, any class that is declared static is a known nested class. The word nested here means that a class that has been declared static inside the scope of another class is known as a static class. A nested static class can work independently on its own as it does not require a reference to the outer class. Static classes are mainly used to provide an outline of their inherited class.

The properties of a static class are as follows:

  • A static class can only contain the static members.
  • A static class cannot access non-static members of the outer class within which it is defined.
  • A static class cannot be instantiated. This means that object creation of static classes is not allowed in Java.

Sample Code:

public class Demo
{
private static String str = “Hello World”;

public static class SDemo
{
public void show ()
{
System.out.println (str);
}
}
public static void main (String args [])
{
Demo.SDemo obj = new Demo.SDemo ();
obj.show();
}
}

 

OUTPUT

Hello World

Explanation

A string variable called str has been declared static in the program’s outer class. This is done because this variable needs to be accessed from the static class, and the static class can only access non-static members of the outer class. If str was declared as non-static, the compiler would show an error because a nested static class cannot access non-static members of the outer class. Another important point that the program elucidates is that when creating an object for the nested static class, an instance of the outer class need not be created. If the nested class was not defined as static, then an instance of the outer class would have to be created.

Final Class

The keyword final in Java means a particular attribute that cannot be changed throughout the course of the program. A final class in Java can be declared in Java using the final keyword. As mentioned before, once a particular value is set as final, that value remains constant. The main purpose of creating a final class is to make a class that is immutable, like the String class. While there are other techniques in Java to make a class immutable, the final method is one such technique. One must remember that a final class cannot be extended.  Thus, It prevents the class from being sub-classed.

Sample Code illustrating a final class

final class A
{
void printmsg ()
{
System.out.println (“Base class method is executed”);
}
}
class B extends class A
{
void printmsg ()
{
System.out.println (“Derived class method is executed”);
}
}
public class Demo
{
static void main (String args [])
{
B obj = new B ();
obj.printmsg();
}
}

 

OUTPUT

/FinalClassExample,java:1l: error: cannot inherit from final class A class B extends A.

Abstract Class

Abstract classes are defined with the keyword abstract. It is not mandatory for abstract classes to contain abstract methods. Therefore, they may or may not contain abstract classes. An instance of an abstract class in Java cannot be created, but it can act as a subclass. Abstract classes are generally incomplete with only abstract method signatures, Therefore, to complete the implementation of abstract classes, it is inherited and given purpose in the sub-classes. When an abstract class is declared to be a subclass, then it is mandatory to give the implementation of the abstract methods along with the method signatures. In such cases, the subclass must be declared an abstract class. Data Hiding can be achieved using abstract classes, In this feature, Java only shows what is relevant to the user while hiding information that is not relevant or represents the implementation of the program. An example of an abstract class is AbstractMap class, which is part of the Collections framework.

Sample Code illustrating an Abstract Class

abstract class mathematicalOperations
{
int x = 60, y = 50;
public abstract void main add ();
}
public class Operation extends MAthematicalOperations
{
public void add ()
{
System.out.println (“The summation of x and y is:” + x + y);
}
public static void main (String args [])
{
MathematicalOperations obj = new Operation ();
obj.add();
}
}

 

OUTPUT

The summation of x and y is: 110

Concrete Class

Concrete Classes are regular classes that are often written with programs in general. It is a derived class that contains methods and fields. The methods are given proper implementation functions. If the class is a sub-class, then implementation of the methods might as well be given in the super class. Such classes are called concrete classes. To think of this differently, concrete classes are regular classes in Java in which all the abstract class methods are implemented. All regular concrete classes can be instantiated directly; that is, concrete classes allow object creation. One thing that should be kept in mind is that concrete and abstract classes are not the same. Java allows concrete classes to extend their parent classes, and such types of classes are used for specific requirements.

Sample Code to Illustrate Concrete Classes

public class ConcreteClass
{
static int product (int x, int y)
{
return x * y;
}
public static void main (String args [])
{
int m = product (7, 9);
System.out.println (“The product of x and y is: ” + m);
}
}

 

OUTPUT

The product of x and y is: 63

Singleton Class

As the name states, a singleton class at any time has only one object. The class works in a way where if you want to create a second instance of the class, the second instance will be created, but it will just point to the first instance of the class. The change is reflected on the single instance variable if any change has been made to the class through any instance. The main purpose of the singleton class is to control access while dealing with database connections and socket programming. A singleton class can be created using the following methods:

  • By creating a private constructor
  • By creating a static method (i.e., by using lazy initialization) that gets back the object of the singleton class.

Sample Code to Illustrate a Singleton Class

public class Singleton
{
private String obS;
private static Singleton instance = null;
private Singleton() throws Exception
{
thi.obS = “Hello World”;
}
public static Singleton getInstance ()
{
if (instance == null)
{
try
{
instance = new Singleton ();
}
catch (Exceptio e)
{
e.printStackTrace();
}
}
return instance;
}
public String getOldObjectState ()
{
return objectState;
}
public void setObjectState (String objectState)
{
this.objectState = objectState;
}
}

 

OUTPUT

Hello World

POJO Class

POJO in Java Language stands for Plain Old Java Object. POJO classes in Java are special types of classes in Java that only contain private variables, setters, and getters. Such classes are used to instantiate Java objects that improve a Java program’s reusability and readability. POJO classes ensure the achievement of encapsulation. As these classes are extremely easy to read and comprehend, these classes are frequently used to carry out several operations.

A POJO class has given properties:

  • POJO does not extend the predefined classes such as Arrays, HttpServlet, etc.
  • POJO cannot contain pre-specified annotations.
  • POJO cannot implement pre-defined interfaces.
  • POJO is not required to add any constructor.
  • All instance variables of POJO must be private.
  • The getter/setter methods in POJO must be public.

Sample Code to Illustrate the Working of a POJO Class

class DemoPojo
{
private double price = 8967.34

public double getPrice()
{
return price;
}
public void setPrice (int price)
{
this.price = price;
}
}
public class POJOExample
{
public static void main (String args [])
{
DemoPojo obj = new DemoPojo();
System.out.println (“The price of the item is ” + obj,getPrice() + “Rs.”);
}
}

 

OUTPUT

The price of the item is 8967.34 Rs.

Inner Class

Inner classes can also be thought of as nested classes. Going by the definition of nested classes, it is the phenomenon where one class is created inside another class. Inner classes are used to achieve encapsulation while logically grouping the classes. The outer class members (including private members) ca be accessed by the inner class. The general syntax for declaring a nested class is as follows:

class OuterClass
{
class NestedClass
{
}
}

 

Nested classes are of two types as follows:

1. Static Nested Class: A static nested class is a nested class (inner class) that is defined as static. It interacts with the static members of the outer class only. An object of a static nested class can be created by using the following syntax:

OuterClass.StaticNestedClass nestedObject = mew OuterClass.StaticNestedClass ();

2. Non-static Nested class: Non static nested classes are called inner classes and it can interact will all members of the outer class. The general syntax for declaring a non static inner class is:

class OuterClass
{
static class StaticNestedClass
{
..
}
class InnerClass
{
…
}
}

 

An example of an Inner Class in Java is:

public class InnerClass
{
public static void main (String args [])
{
System.out.println (“This is the outer class”);
}
class InnerClassIn
{
public void printinner()
{
System.out.println (“This is the inner class”);
}
}
}

 

Types of Inner Classes:

  • Local Classes or Method Local Inner Class
  • Anonymous Classes or Anonymous Inner Class

Local Inner Class

Local Inner Classes are a type of inner class that is defined inside a block where a block signifies the body of a method (a group of statements enclosed in braces). Due to defining inside a block, these classes are also known as method local inner class. They can access the instance members of the class. Therefore, they are non-static classes. A local inner class can be easily defined inside the body of a method; however, the classes should be instantiated in the body of the block in which it has been declared.

Whenever a Java program containing an inner class is compiled, the compiler makes two class files, namely Outer.class and Outer$1Inner.class. These two class files denote, respectively, the outer class and the inner class (that contains the reference for the outer class).

Sample Code to Illustrate the working of a Local inner class

public class OuterClass
{
private void getValues()
{
int sum = 20;
class InnerClass
{
public int num_Divisor;
public int num_remainder;
public InnerClass()
{
num_divisor = 4;
num_remainder = num_sum % num_divisor ;
}
private int getDivisor()
{
return num_divisor;
}
private int getRemainder ()
{
return num_sum % num_divisor;
}
private int getQuotient ()
{
System.out.println (“Now inside the inner class”);
return sum / divisor;
}
}
InnerClass ic = new InnerClass();
System.out.println (“Divisor = ” + ic.getDivisor());
System.out.println (“Remainder = ” + ic.getRemainder());
System.out.println (“Quotient = ” + ic.getQuotient());
}
public static void main (String ags [])
{
OuterClass oc = new OuterClass();
oc.getValue();
}
}

 

OUTPUT:

Divisor = 4
Remainder = 0
Quotient = 5

Anonymous Inner Class

Anonymous Inner Class performs the same basic functions as local classes. The only difference is that such classes do not have a name and have only one object created for the class. These classes are generally implemented to make the code more concise and generally used when the local classes are only used once. Such classes can be created in the following ways:

  • By using an interface
  • By declaring the class concrete and abstract

Syntax:

DemoClass obj = new DemoClass ()
{

public void demoMethod ()
{
}
};

 

An Example of an Anonymous Inner Class is:

interface Score
{
int run = 321;
void getScore ();
}
public class AnonymousClass Example
{
public static void main (String args [])
{
Score s = new Score ()
{
@Override
public void getScore()
{
System.out.println (“Score is ” + run);
}
};
s.getScore ();
}
}

 

OUTPUT:

Score is 321

Java also provides users the option of implementing a wrapper class which is discussed below.

Wrapper Class

Wrapper Classes represent a collection of Java classes that mainly deal with the primitive data type classes of Java. For every primitive type, there are corresponding Java wrapper classes. When dealing with data type conversions involving converting a primitive type to an object or vice versa, these classes come into play.

Primitive Types and corresponding wrapper classes are given in the table below:

Primitive TypeWrapper Class
booleanBoolean
intInteger
charCharacter
doubleDouble
floatFloat
longLong
byteByte
shortShort

Sample Code to Illustrate the working of a Wrapper Class

public class WrapperExample
{
public static void main (String args [])
{
byte x = 0;
Byte byteobj = new Byte (x);
int y = 23;
Integer intobj = new Integer (y);
char c = ‘m’;
Character charobj = c;
//printing values from objects
System.out.println (“Byte object byteobj: ” + byteobj);
System.out.println (“Integer object intobj: ” + intobj);
System.out.println (“Character object charobj: ” + charobj);
}
}

 

OUTPUT

Byte object byteobj: 0
Integer object intobj: 23
Character object charobj: m

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author