Java Classes and Objects

In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes.

An object in Java is the physical as well as logical entity whereas a class in Java is a logical entity only.

 

What is an object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.

An object has three characteristics:

  • State: represents the data (value) of an object.
  • Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
  • Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

 

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Classes
  • Objects
  • Instance
  • Method
  • Message Passing

 

Create a Class

class <class_name>{  
    field;  
    method;  
}  


public class StudyCruxClass {
  int x = 6;
}

 

Create an Object

public class StudyCruxClass {
  int x = 7;

  public static void main(String[] args) {
    StudyCruxClass myObj = new StudyCruxClass();
    System.out.println(myObj.x);
  }
}

 

Multiple Objects

You can create multiple objects of one class:

public class StudyCruxClass {
  int x = 5;

  public static void main(String[] args) {
    StudyCruxClass myObj1 = new StudyCruxClass();  // Object 1
    StudyCruxClass myObj2 = new StudyCruxClass();  // Object 2
    System.out.println(myObj1.x);
    System.out.println(myObj2.x);
  }
}

 

Using Multiple Classes

public class StudyCruxClass1 {
  int x = 5;
}

class OtherClass {
  public static void main(String[] args) {
    StudyCruxClass1 myObj = new StudyCruxClass1();
    System.out.println(myObj.x);
  }
}