Classes & Objects

In Java, everything is associated with classes and objects. In other words, one of the basic concepts of Object-Oriented Programming is classes and objects that revolve around real-life entities.

Class –

  • A class is just a group of objects that contains common properties.
  • In other words, it is a logical entity.
  • A class in Java can contain fields, methods, constructors, blocks, interfaces, etc.
  • Syntax – class <class_name>{  //fields and  methods  }  
  • Classes are classified into two categories –
    • Built-in Classes
      • Built-in classes are the one that comes bundled within predefined packages in Java and are provided as a part of JDK.
      • Examples –
        • java.lang.String
        • java.lang.System
        • java.lang.Exception
        • java.lang.Object
    • User-Defined Classes
      • A user-defined class is the one that is created by the user.

Object –

  • An object is an instance of a class
  • In other words, it is a logical as well as a physical entity.
  • Object consist of state(data), behavior(functionality) and identity(unique id identified by JVM).
  • For instance –
    • a book
      • state – size, color, author
      • behavior – reading
    • a car
      • state – color, type, average, manufacturer
      • behavior – driving
  • One can create an object of a class in the following ways –
    • new keyword
    • newInstance() method
    • clone() method
public class Book {
	public Book(String name) {
		System.out.println(name);
	}
	public static void main(String args[]) {
		//object of class Book created using new Operator
		Book book1 = new Book("R.D. Sharma");
		
		//object of class Book created using clone method
		Book book2 = (Book)book1.clone();
		
		//object of class Book created using newInstance method
		Book book3 = (Book) Class.forName("Book").newInstance();
	}
}
What is Object Cloning in Java?

Object cloning is nothing but creating a copy of an object. To achieve that, clone() is used in java. For instance –

Car obj1 = new Car();
Car obj2 = (Car)obj1.clone();