Classes and Objects in Java

Classes and Objects in Java

by Sanjay Nair February 17, 2018
  • In this tutorial we will discuss about java classes and objects.
  • In order to design a program using object oriented programming technique, we use classes and objects.
  • Object is considered as real, physical entity whereas the class is considered as the logical entity.

Objects in Java

  • Any entity that has a state and exhibits certain behaviors are called objects. For egs bike, pen, car, chair,
  • table etc. The object can be either physical or logical(conceptual). A logical entity can be a railway
  • reservation system.

An object exhibits three characteristics:

state: This represents the value of the object.

behaviour: This represents the behaviour of the object. egs deposit,withdraw etc.

identity: The object identity is implemented by Java via a unique id. This unique is not visible to the

external user but it is used by the JVM to uniquely identify the object

Example: Car is an object. Its name is BMW, color is blue.

  • These represent the states.
  • The car is used to travel. So travel is its behaviour.
  • The instance of a class is known as an object. From the class we create objects. Hence we can say that the instance of the class is an object.

Class in Java

  • A class constitutes of a group of objects having common properties.
  • It is a structure from which objects are made.
  • Class is a conceptual or logical entity.

A Java class contains

  • variables
  • methods
  • constructors
  • blocks
  • nested class and interface

How to declare a class

 

A Variable in Java

  • A variable declared inside a class but outside a method is called an instance variable in Java.
  • The instance variable doesn’t get memory during compilation but allocated memory only during execution.
  • Hence it is called an instance variable.

Methods

  • A method exposes the behaviour of an object just like a function.

The new keyword.

  • The new keyword is used to allocate memory during runtime. The objects get memory from Heap Memory Area.
  • An Example of an object and a class(where main is inside the class)

Output:

1

Sam

 

  • An Example of an object and a class(where the main is outside the class)

Compiling and running this program, we get

Output:

1

Sam

You may also like

Leave a Reply