Skip to content

Java Class | Declaration | Types | Constructor | Example

  • by

What is the Java Class? 

Java Class is a blueprint (template or prototype) for any object or instance. The class has a group of common properties, methods, blocks, nested classes, etc, which are common for any object.

A Class and objects are Object Oriented Programming  (OOP) concepts.  Java supports all OOP concepts because it is written on the OOP fundamentals. One by one we will understand and learn the all-OOPs fundamentals.

Java Class Declaration Types Constructor Example

Let’s see the example you want a build a car. Then think about car class have all the details about the engine, tyers, body, etc parts. So based on these car classes we can build a car, where you can create an object from a Car class. About an object or instance, we will discuss in a later tutorial.

Java class declaration

Here is simple syntax and structurer look.

class <class_name>{  
    field;  
    method;  
}

Java class Example

The class name is Bulb with an Instance variable and 2 methods to control bulb function On/Off.

public class Bulb {

    // instance variable
    private boolean isOn;

    // method
    public void turnOn() {
        isOn = true;
    }

    // method
    public void turnOff() {
        isOn = false;
    }
}

Types of classes in java

Some of the common type of class in Java is as follows:-

  • Wrapper Class
  • Mutable Class
  • Abstract Class
  • Final Class
  • Anonymous Class
  • Input-Output Class
  • String Class
  • System Class
  • Network Class

According to Access Modifier four type of class:-

  • Public Class
  • Private Class
  • Protected Class
  • Default Class

According to Inheritance:-

  • Supper Class
  • Sub Class.

Java class constructor

The constructor is used to create the object (instance) of the class in java. It’s similar to write a method and which is used to initialize the object.

When is a Constructor called?

When we create a new object of a class that time at least one Constructor has called. If there is no constructor defined then by default will call. It is invoked to assign initial values to the data members of the class.

Rules for Constructor:

  • The constructor must be same as class name.
  • A constructor can’t be abstract, final, static and Synchronized in Java.
  • You can use Access modifiers in constructor declaration to control its access in classes.

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.5 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Class Examples are in Java 11, so it may change its different from Java 9 or 10 or upgraded versions.

Leave a Reply

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