DEV Community

PRIYA K
PRIYA K

Posted on

Class in Java


Classes and Objects in Java - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org


Java - Classes and Objects

Java is an Object-Oriented programming language. In Java, the classes and objects are the basic and important features of object-oriented programming system, Java supports the following fundamental OOPs concepts In this tutorial, we will learn about

favicon tutorialspoint.com

In Java, classes and objects form the foundation of Object-Oriented Programming (OOP).
we can say a class is a data type of an object type.
In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and manipulated through the objects.
A class is a blueprint or template used to create objects, that share common properties and behavior..
It defines the structure and behavior that its objects will have, acting as a user-defined data type.
An object is an instance of a class. It represents a specific entity created from the class template.
It is a logical entity. It can't be physical.
Providing initial values for member variables and implementations of behaviors (methods). An object is an instance of a class, representing a specific entity with a defined state and behavior.

A class is a blueprint that defines data and behavior for objects. It groups related fields and methods in a single unit. Memory for instance members is allocated when an object is created, while static members are allocated when the class is loaded into memory.

Acts as a template to create objects with shared structure.
Does not occupy memory for fields until instantiation.
Can contain fields, methods, constructors, nested classes and interfaces.
Enter fullscreen mode Exit fullscreen mode
class Student {
    int id;
    String n;

    public Student(int id, String n) {
        this.id = id;
        this.n = n;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(10, "Alice");
        System.out.println(s1.id);
        System.out.println(s1.n);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
10
Alice

Core Components
Fields (Attributes): Variables that represent the state or data of an object (e.g., String color for a Car class).
Methods (Behaviors): Functions that define what the object can do (e.g., drive() or brake()).
Constructors: Special blocks of code used to initialize new objects when they are created
Blocks:
Nested class and interface:

Basic Syntax
To define a class, use the class keyword followed by the class name (which should start with an uppercase letter ):

public class Dog {
    // Field
    String breed;

    // Method
    void bark() {
        System.out.println("Woof!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Syntax to declare a class:
class {
field;
method;
}

A class in Java defines a new data type that can include fields (variables) and methods to define the behavior of the objects created from the class.

Syntax

class ClassName {
    // Fields
    dataType fieldName;

    // Constructor
    ClassName(parameters) {
        // Initialize fields
    }

    // Methods
    returnType methodName(parameters) {
        // Method body
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation:
ClassName: The name of the class.
fieldName: Variables that hold the state of the class.
Constructor: A special method used to initialize objects.
methodName: Functions defined within the class to perform actions.

Properties of Java Classes
A class does not take any byte of memory.
A class is just like a real-world entity, but it is not a real-world entity. It's a blueprint where we specify the functionalities.
A class contains mainly two things: Methods and Data Members.
A class can also be a nested class.
Classes follow all of the rules of OOPs such as inheritance, encapsulation, abstraction, etc.

Key Types of Classes
Concrete Class: A standard class where all methods are fully implemented; it can be instantiated directly.
Abstract Class: Declared with the abstract keyword. It cannot be instantiated and is meant to be a base for other classes to inherit from.
Final Class: A class that cannot be inherited or subclassed.
Inner/Nested Class: A class defined inside another class to logically group components.
Singleton Class: A specialized class designed to ensure only one instance of it ever exists.

Types of Class Variables
A class can contain any of the following variable types.

Local variables
− Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

**Instance variables** 
Enter fullscreen mode Exit fullscreen mode

− Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

**Class variables** 
Enter fullscreen mode Exit fullscreen mode

− Class variables are variables declared within a class, outside any method, with the static keyword.

Creating (Declaring) a Java Class
To create (declare) a class, you need to use access modifiers followed by class keyword and class_name.

Syntax to create or declare a Java class

access_modifier class class_name{
  data members;
  constructors;
  methods;
  ...;
}

Enter fullscreen mode Exit fullscreen mode

Example of a Java Class
In this example, we are creating a class "Dog". Where, the class attributes are breed, age, and color. The class methods are setBreed(), setAge(), setColor(), and printDetails().

// Creating a Java class
class Dog {
  // Declaring and initializing the attributes
  String breed;
  int age;
  String color;

  // methods to set breed, age, and color of the dog
  public void setBreed(String breed) {
    this.breed = breed;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public void setColor(String color) {
    this.color = color;
  }

  // method to print all three values
  public void printDetails() {
    System.out.println("Dog detials:");
    System.out.println(this.breed);
    System.out.println(this.age);
    System.out.println(this.color);
  }
}

Enter fullscreen mode Exit fullscreen mode

Important Rules
Naming Conventions: Use camelCase for variables and methods, and PascalCase for class names to improve readability.

One Public Class: A single Java source file can only have one public class, and the filename must match that class name (e.g., Main.java for public class Main).
Memory: A class itself does not occupy memory; memory is only allocated on the heap when an object is instantiated using the new keyword.
The Object Class: In Java, every class automatically inherits from the built-in Object class, which provides fundamental methods like toString() and equals()

Top comments (0)