Class and Object in Java

Class:

The class is defined as a blueprint for an object. You can create as many objects as you like for a single class. Class is the bind of attributes and methods. It is often referred to as a template to create an object. Class is a user-defined data type. Java allows a programmer to create your type using classes. In java String is not a primitive data-type it is class.


Syntax:
modifier class ClassName { //class header
//fields
//constructor
//methods
}
As seen from syntax the class is a combination of fields, constructor, and methods. 
Modifiers are specified the accessibility scope. Modifiers are applicable for class, fields, constructors, and methods.
constructor is referred to as a special type of method in java. The name of the constructor is the same as the class name. The constructor doesn’t have any return type. The objective of a constructor is to initialize the newly created object. 
method is a block of code or collection of statements to perform some task. For example, we use str.length() method to find out the length of the String str. There is a block of code in length() method to find and return as a value.

Example:
public class Dog {
    private String breedName;
    private String color;
    private float weight;

public void Eat() {
    System.out.println(“Eating…”);
}

public void Bark() {
    System.out.println(“Bow! … Bow!”);
}
public void Sleep() {
    System.out.println(“Sleeping…”);
}
}

Object:

An object is defined as an instance of the class. The object is having two characteristics states (attributes) and behaviours
If you consider a dog is an object. The states or attributes of the dog are Breed, Age, and Colour. Behaviours are Eat, Sleep, and Bark.

We can create as many objects as you like for a single class. The dog is not a real-world object until you create an object for that class.
 Dog dog = new Dog();
Her we have created an object for the Dog class using the new keyword.

Leave a Comment

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

Scroll to Top