---
# System prepended metadata

title: Classes and Objects in Java - Scaler Topics

---

---
title: Classes and Objects in Java - Scaler Topics
description: Learn about Classes and Objects in Java by Scaler Topics. In this article, we will be discussing the definition and characteristics of classes and objects in java.
author: Dave Amiana
category: Java
---


:::section{.main}

Java is a class-mandatory programming language that imposes an object model on the developer. Classes serve as a prototype for representing objects that group pieces of data and methods. An Object is an entity that has a state and behaviour. As a result, we think of a problem in the world in terms of objects and perform actions by calling their associated set of methods.
The concept of class and object in Java is quite useful in development as well as solving sophisticated problems.
:::
:::section{.main}
## Java Classes

In Java, a class serves as a blueprint for creating objects with similar characteristics and behaviours. It encapsulates properties and meaning within a specific context, like a Car class representing individual cars. Classes maintain common attributes and behaviours, facilitating efficient object creation and management in programming.


### Properties of Java Classes

* A Java class serves as a blueprint for creating objects and doesn't take up memory.
* It comprises variables of various types and methods. You can include data members, methods, constructors, nested classes, and interfaces within a class. 
* It acts as a template for organizing and defining the behaviour of objects in your program.


### Syntax of Java Classes
 One can declare a `public`, `private`, or `default` class as:

```java 
public class PublicClassName {
    // declaration section for 
    // methods and attributes
} 

private class PrivateClassName {
    // declaration section for 
    // methods and attributes
} 

class DefaultClassName {
    // declaration section for 
    // methods and attributes
} 
```

### Example of Java Class

Lets see an example for syntax of class and object in java:
```java
class Car{
    // declaration of private attributes
    private String modelName;
    private String owner;
    private int regNumber;
    
    // declaration of public constructor
    public Car(String modelName, String owner, int regNumber){
        this.modelName = modelName;
        this.owner = owner;
        this.regNumber = regNumber;
    }
    
    // declaration of public methods
    public void startEngine(){
        System.out.println("Engine is starting ....");
    }
    
    public void accelerate(){
        System.out.println("Car is accelerting ...");
    }
    
    public void stop(){
        System.out.println("Car is stopping ...");
    }
    // prints car attributes
	public void showCarInformation(){
        System.out.println("The car is owned by: " + this.owner);
        System.out.println("Car Model: " + this.modelName);
       	System.out.println("Registration Number: " + String.valueOf(this.regNumber));
    }
}
```

The code above shows a template for how class and object in java are implemented. The `Car` class contains `private` attributes hidden from the outside world. That means calling out the `modelName` attribute outside the scope of the `Car` class will raise a compiler error. 


### Components of Java Class



#### Class Name

The class name pertains to a namespace in which we can associate coherent methods and data. In our code example, both `ClassA` and `ClassC` pertain to a class's namespace. Java uses a `PascalCase` naming convention for classes.

#### Class keyword

The `class` keyword signifies that we intend to begin creating a prototype of an object. 

#### Constructors

Java constructors initialize an instantiated object based on preconditions set by the caller. Constructors can be parameterized or specified without parameters. 

A class may contain multiple constructors that configure an instantiated object accordingly. A constructor is a specialized method that must be defined with: 
1. The same name as the class. 
2. Does not return an explicit type.
3. Cannot be `synchonized`,`abstract`,`static`, and `final`.

We say a **constructor** is defined in default when it contains no parameters. Default constructors are intended to initialize an object when no arguments are passed into it. A constructor is overloaded whenever we specify parameters.


```java
class Cube{
    // ...
    private double side = 1.0;
    public Cube(){
        System.out.println("Cube Default constructor is called");
    }
    
    public Cube(double side){
        System.out.println("Cube is instantiated with specified value " + side);
        this.side = side;
    }
}
```

#### Modifiers

Java supports access modifiers to provide different restriction levels in different program parts. In other words, access modifiers control which code sections can invoke the name of a class, method, or attribute. There are two contexts in which an access modifier may be defined: memberwise access and class-level access. 


Suppose that we subclass `Sphere` from `PackageTwo` in `AbstractShape` from `PackageOne` as follows: 

![image alt](https://scaler.com/topics/images/modifiers-in-java-classes.webp)

Suppose further that in each class, an entity exists with different modes of access. 

Summary of the visible entities relative to `ClassA`:

| Modifier    | `Sphere` | `AbstractShape` | `Cube`      |
| :-----------: | :--------: | :---------------: | :-----------: |
| `public`    | visible  | visible         | visible     |
| `protected` | visible  | visible         | not visible |
| [default]   | visible  | visible         | not visible |
| `private`   | visible  | not visible     | not visible |

In general, the table translates to:

| Access Modifier | Within Class | Within Subclass | Within package | Outside Package |
| :---------------: | :------------: | :---------------: | :--------------: | :---------------: |
| Private         | Visible      | Not Visible     | Not Visible    | Not Visible     |
| [Default]       | Visible      | Not Visible     | Visible        | Not Visible     |
| Protected       | Visible      | Visible         | Visible        | Not Visible     |
| Public          | Visible      | Visible         | Visible        | Visible         |



#### Body

The body of the class contains the implementation of associated methods and attributes within that class. A body may contain the following:
- Methods contain the set of actions in the object definition,
- Constructor, which is a unique method that initializes the state of an object upon its creation,
- Attributes that define the internal states of the class, and
- Variables that contain the values of an attribute within the class
In addition, methods and attributes may be specified with modifiers that regulate their accessibility.


#### Superclass (or Supertypes)

![superclass](https://scaler.com/topics/images/superclass.webp)

Superclass may be implemented as abstract class or base class types because they contain a group of standard features that are extended in a subclass. Because subclass *extends* the contents of a superclass, Java uses the keyword `class [classname] extends [superclass]`. 

Superclass contains the following features that extend your Object-Oriented Design:

1. A superclass represents a set of common properties inherited by its subclass. A subclass may modify methods that maintain the structure of an interface with altered behaviour.
2. Supertypes may implicitly cast a type into its subtype when the situation calls for it. 

Suppose we intend to pass an argument in a function. Since Java expects type information before the name of an argument, we need to include it. Without supertypes, we would have to overload multiple functions to account for executing the same method in different types.


```java
public void displayInformation(Sphere sphere){
    System.out.println("The shape is " + sphere.nameOfObject());
    System.out.println("The surface area of the sphere is " + sphere.area());
    System.out.println("The volume of the sphere is " + sphere.area());
}
```



To get rid of code redundancy, supertypes are a great way for the compiler to deduce the type information based on the argument passed into the function. 

```java
public void displayInformation(AbstractShape shape){
    System.out.println("The shape is " + shape.nameOfObject());
    System.out.println("The surface area of the " + 
                       shape.nameOfObject() + " is " + shape.surfaceArea());
    System.out.println("The volume of the " + 
                       shape.nameOfObject() + " is " + shape.volume());
}
```

Now, `displayInformation()` can accept any subtypes that extend from `AbstractShape`, such as the class `Cube`.

#### Interface

Because Java does not support multiple inheritance, subclasses can only extend one superclass. This limitation is addressed by a Java construct known as Interfaces.

An interface is a set of declarations that form a contract between an object and the outside world. If the class intends to use the interface, all its methods must appear in the source code; otherwise, the program will not compile. All methods defined in an interface default to `public final static`.




```java
interface Resizeable{
    public abstract void resize(double scale);
}

class Sphere extends AbstractShape implements Resizeable{
    //...
    @Override
    public void resize(double scale){
        this.radius *= scale; 
    }
}
```

Note that since Java 8, an interface can define a default method with the `default` keyword.

```java
public default void resize(){
    // default implementation of the resizing function
}
```
:::
:::section{.main}

## Java Objects

[Objects](https://www.scaler.com/topics/object-in-java/) model an entity in the real world. Modelling entities require you to identify the state and set of actions that can be performed in that object. This way of thinking is key to object-oriented programming.

- An Object is the root class of all instantiated objects in Java.
- Instantiated objects are names that refer to an instance of the class.


### Declaring Objects in Java

```java
Sphere sphere = new Sphere(10);
```

The first two tokens in the code snippet above declare an object in Java. When we read into the code, it means creating a new instance of `Sphere` and initializing its radius to `10`.


### Initializing a Java object

As mentioned, a constructor initializes an object in Java. Multiple class constructors mean that instantiating an object can have different signatures. We use the `new NameOfClass([arguments_values]))` to initialise a new object. There are mainly three ways to initialize an object in java:


#### By Reference Variable

A constructor may accept reference type parameters.

> Recall: All object types in Java are passed by reference.

**Example: Initialization through reference**

```java
class Cube extends AbstractShape{
    private double side;
    public Cube(Cube cubeReference){
        this(this.side);
    }
}
```

The above code effectively copies the content of arguments passed in the constructor of type `Cube`.



#### By method

An object may be initialized with a setter function that alters the class's internal state and may be accessed with a getter function. This initialization allows only one instance of the class to be modified **dynamically**: one can alter that of the object at runtime. 



**Example: Initialization through a method**

```java
class Cube extends AbstractShape{
	private double side;
    
    public Cube(){
    	System.out.println("Cube is instantiated.");    
    }
    public void setSide(double side){
        this.side = side;
    }
    
    public double getSide(){
        return this.side;
    }
    // ...
}

class Main{
    public static void main(String [] args){
        Cube cube = new Cube();
        cube.setSide(5.7);
    	System.out.println("Internal state of the cube: " + cube.getSide()); 
        cube.setSide(11.2);
    	System.out.println("Internal state of the cube: " + cube.getSide());    
    }
}
```


#### By constructor

Finally, an object may be initialized by specifying arguments passed in a constructor. A constructor is a unique method that initializes the state of class instance. 


:::

:::section{.main}

## Different Ways to Create Objects in Java


There are different ways to instantiate an object in Java; this section aims to discuss and implement each style.

###  Using new Keyword

This is the most direct form of object creation in Java. This style tells Java to initialize a class instance and assign a reference to it in a named object, in this case, `cube`.

  ```java
  Cube cube = new Cube(4.5);
  ```

### Using Class.forName(String className) Method
 
This style can be attained if the class has a public constructor. The `Class.forName()` method does not yet instantiate an object; to do so, the `newInstance()` has to be typecast in the given class. 

  ```java
  class Cube {
      public Cube(){
          System.out.println("Cube is instantiated.");
      }
      // ...
  }
  
  public class Main{
      public static void main(String[] args) throws ClassNotFoundException, 
                                                    InstantiationException,
                                                    IllegalAccessException{
          Class obj = Class.forName("Cube");
          Cube cube = (Cube)obj.newInstance();
      }
  }
  ```

### Using clone() Method

It requires the object to implement a `Cloneable` interface. Since objects are passed by reference in Java, changes that happen somewhere in the program affect the internal state of that object. In cases where we do not want unintended side effects to happen, we can copy the entire contents of an object and treat it independently. 

  ```java
  class Cube implements Cloneable{
      @Override
      protected Object clone() throws CloneNotSupportedException {
          return super.clone();
      }
      
      public Cube(double x){
          System.out.println("instantiated with " + x);
      }
      // ...
  }
  
  public class Main{
      public static void main(String[] args) throws CloneNotSupportedException{
          Cube cube1 = new Cube(4.5); 
          Cube cube2 = (Cube)cube1.clone();
      }
  }
  ```
### Deserialization

It converts a stream of bytes into an object. We must implement the `Serializeable` interface in the class to implement this style.

  ```java
  class Cube implements Serializeable{    
      public Cube(double x){
          System.out.println("instantiated with " + x);
      }
      // ...
  }
  
  public class Main{
      public static void main(String[] args) throws Exception{
          Cube cube1 = new Cube(4.5); 
          Cube cube2 = (Cube)cube1.clone();
      }
  }
  ```

:::

:::section{.main}

## Anonymous Objects in Java


Anonymous objects are nameless entities that may be used for calling a specific method defined in a class without needing the entire class – nameless objects mean the class instance does not have a reference.

```java
System.out.println(new Cube(5.5).surfaceArea());
```
:::

:::section{.main}

## Creating Multiple Objects by One Type
 
One can create multiple objects within a container type in Java, such as `List`, `Array`, `ArrayList`, `Queue`, and `Stack`. 



**Real World Example: `Account`**

```Java
import java.util.ArrayList;
import java.util.List;

class Account{
    private String accountName;
    private String accountHolder;
    private String accountNumber;
    
    Account(String accountName, String accountHolder, String accountNumber){
        this.accountName = accountName;
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
    }
}

class Main{
   public static void main(String[] args) {
      List<Account> accountList = new ArrayList<Account>();

      accountList.add(new Account("BDO", "Jenifer Alvez", "001-237-9900"));
      accountList.add(new Account("BPI", "John Ronel", "001-247-9982"));
      accountList.add(new Account("JPMC", "Ross Geller", "001-239-9920"));
      accountList.add(new Account("BDO", "Jenifer Adriana", "001-217-9980"));
       
      for(Tester tester : testerList){
         System.out.println(tester.getData());
      }
   }
}
```

:::

::: section{.main}

## Difference between Classes and Objects in Java

| Class |  Object| 
| :--------: | :--------: | 
|  A class is a blueprint for declaring and creating objects.        |   An object is a class instance that allows programmers to use variables and methods from inside the class.        | 
| Memory is not allocated to classes. Classes have no physical existence.         | When objects are created, they are allocated to the heap memory.   | 
|  You can declare a class only once.        |       A class can be used to create many objects.   | 
| Class is a logical entity.         |    An object is a physical entity.   | 
|   We cannot manipulate class as it is not available in memory.       |  Objects can be manipulated.        | 
|  Class is created using the `class` keyword like `class Dog{}`        |   Objects are created through `new` keyword like `Dog d = new Dog();`. We can also create an object using the `newInstance()` method, `clone()` method, factory method, and deserialization.      | 
|  Example: `Mobile` is a class.        |  If ``Mobile`` is the class, then `iphone`, `redmi`, `blackberry`, and `samsung` are its objects with different properties and behaviours.        | 
|  Classes can have attributes and methods defined.       |  Objects can have specific values assigned to their attributes.      | 
|  Classes serve as blueprints for creating objects.       |  Objects represent specific instances created from a class.      | 

To learn about differences between class and object in Java depth, visit [Class Vs. Object: What are the Differences?](https://www.scaler.com/topics/difference-between-class-and-object/)

:::

:::section{.summary}

## Conclusion

- Objects are models of an entity that exist in the real world. Object-oriented thinking refers to everything as objects that contain a set of **states** and **behaviour**. 
- Class provides a prototype for describing the content of an instantiated object. 
- The most straightforward declaration of a class contains a **class name** and a **class body**, which may contain `constructors`, `methods`, and `attributes`. 
- A class may extend features from another class, which preserves the interface of standard features and allows a subclass to specialize methods accordingly. 
- Classes may take in three forms: **Abstract, Base, and Concrete class**.
- Java does not support multiple inheritance; Interfaces substitute multiple inheritance by defining a contract between classes. 
:::
