×

Class vs Object in Java

Java :

Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems in the year 1996 as java 1.0 . It is a high level, robust, secured programming language. Java consists of Java Virtual Machine (JVM) which uses the execution engine and converts the class file into executable file (.class file to .exe file). The execution engine consists of Interpreter and Just In Time(JIT) compiler. In Java we will create classes and then we will create objects.

Class :

Class is as a template or blue print which is used to create objects. It is also used to define the data types and methods. Class is a kind of data type which not primary or built in data type and therefore it is known as an user defined data type. User defined data types are also  known as non – primitive data types. Class is built in java program in class section and also in class with main section.

Class is also used to define the nature of the object. We can also create multiple objects for a single class. Class does not occupy space or memory but the objects created for a class occupies the memory under heap area.

Syntax to define a class :

The syntax to define a class is as shown below :

class   Class_name

While defining the class name the name of the class should be always start with the capital letter. A class within it consists of variables , constructors and methods. The file name should be saved as the class name which consists of the main section.

1)Variables : Variables are declared in the class section. It is  used to store a value and access the value. The variables can be declared using several data types.

Syntax to define a variable :

The syntax for defining a variable as shown below :

data_type    variable_name;

There are different types of variables. They are shown below :

  • Instance variable
  • Local variable
  • Static variable or Class variable or Global variable

Instance Variable : Instance variables are also known as the non static variables. They are defined within the class and also below the class. There can also be defined in class outside the method block or outside the constructor block.

Local Variable : Local variable can be defined within the method parameters. It can also be defined within the method block or the constructor block. These variables are also called as non static variables.

Static variable : Static variable is also known as class variable or also known as global variable. It can be defined any where within the class. But we should use static key word before the variable name. Therefore it is known as static variable.

2)Constructors : Constructor is used to construct the instance variable values before creating an object. We should follow certain rules to define a constructor. The rules that should be follow to define a constructor are as shown below :

  • Constructor name and class name must be same.
  • In constructors there is no return data type.
  • In constructors we can pass one or more parameters.

Syntax to define a constructor :

The syntax for defining a constructor is as shown below :

Name_of_the_class( )

There are different types of constructors in java. They are as shown below:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor or Reference Constructor
  • Overloading Constructor

3)Methods : Method in java is also known as a function in C language. Method may have return data type and we can also pass parameters to the methods.

Syntax to define a method :

The syntax for defining a method is as shown below :

return data type   method_name ( passing  parameters )

There are different types of methods. The different kind of methods are as  shown below :

  • Instance Method
  • Static Method or Class Method or Global Method

Instance Method: Instance method is a method that is defined just below the class. Instance methods are also known as non static methods. There can also be defined in class outside the method block or outside the constructor block.

Static Method: Static method is also known as class method or also known as global method. It can be defined any where within the class. But we should use static key word before the method declaration. Therefore it is known as static method.

Example :

Let us see an example with the following program as shown below to define a class :

import java.io.*;
class Person     // class section
{
int eid;     //  instance variables
String ename;
float esal;
Person( )     // constructor ( default constructor )
{
System.out.println(“eid = “ + eid );
System.out.println(“ename = “ + ename );
System.out.println(“esal = “ + esal );
} // person( )
void show ( int ei , String en , float es )       // local variables
{
System.out.println( “ Storing local variables into instance variables “ );
eid = ei ;
ename = en ;
esal = es ;
System.out.println(“eid = “ + eid );
System.out.println(“ename = “ + ename );
System.out.println(“esal = “ + esal );
} // show
} // person class
class Demo        // class with main section
{
public static void main ( String args[ ] )
{
Person obj = new Person ( ) ;
obj.Person( ) ;
obj.show( 101 , “sai” , 15000.59f ) ;
} // main method
} // demo class

Output :

eid = 0
ename = null
esal = 0.0f
Storing local variables into instance variables
eid = 101
ename = sai
esal = 15000.59

Object :

Object can be created for a class. An object is an entity with some identifiable characteristics , state and behavior. We can also say that the objects are also known as the instance of each and every class.

The classes does not have any storage or memory. After creation of objects to the class there will be storage of memory under heap area. For objects the memory is stored under heap area.

An object is also known as a data field with uniqe attribute and also with unique behavior. It is also a member of java class. These objects are created from the template or blue print and these are also known as classes. The objects are created at the run time or in a dynamic way.

Syntax for creating an object :

Class_name    object_name  =  new    Class_name ( ) ; 

In creating an object for the given class we will use the “ new “ operator. The new operator is used to create memory under the heap area. We can also create multiple objects for a single class.

We can print the reference of an object using the keyword “ hashCode ( ) “ . The hashCode ( ) prints the reference of the object. The reference of the object is in the  hexa - decimal form.

hashCode ( ) :

The method hashCode ( ) is a built in method. The method hashCode ( ) is used in printing the reference of the given object. The reference is also known as hash value. So we can say that by using the hashCode ( ) method we can return the hash value or the reference of an object.

Example :

Let us see an example by printing the reference of an object or the hash value of an object by calling hashCode ( ) method.

import java.io.*;
class Person
{
int id;
void show ( )
{
System.out.println(“id = “ + id );
}
}
class Demo
{
public static void main ( String args [ ] )
{
Person obj = new Person ( ) ;
obj.show( );
System.out.println( “ The reference of an object obj is “ + obj.hashCode( ) );
} // main method
} // demo class

Output:

id = 0
The reference of an object obj is 1920764578

We also use the “ instanceof “ operator to check whether an object belongs to a particular class or not.

instanceof :

The operator instanceof is mainly used to check whether the object is an instance of a particular class or not. We can also use instanceof operator to check whether the objects of sub class is an instance of the super class or not.

Example:

Let us see an example to check whether an object is an instance of the particular class or not using the operator “ instance of “ as shown below :

import java.io.*;
class Person
{
 int id ;
 void show ( )
{
System.out.println ( “ id = “ + id ) ;
} // show
} // person class
class Demo
{
 public static void main ( String args [ ] )
{
Person obj = new Person ( ) ;
obj.show( );
boolean result = obj instanceof Person ;    // instanceof operator
System.out.println( “ Checking whether the obj is an instance of person or not “ ) ;
System.out.println ( “ result = “ + result ) ; 
boolean result1 = obj1 instanceof Person ;    // instanceof operator
System.out.println( “ Checking whether the obj1 is an instance of person or not “ ) ;
System.out.println ( “ result1 = “ + result1 ) ; 
} // main method
} // demo class

Output:

id = 0
Checking whether the obj is an instance of person or not
true
Checking whether the obj1 is an instance of person or not
false

Now let us see an example for creating an object to a particular class by using the following code.

Example:

import java.io.*;
class Person     // class section
{
int eid;     //  instance variables
String ename;
float esal;
Person( )     // constructor ( default constructor )
{
System.out.println(“eid = “ + eid );
System.out.println(“ename = “ + ename );
System.out.println(“esal = “ + esal );
} // person( )
void show ( int ei , String en , float es )       // local variables
{
System.out.println( “ Storing local variables into instance variables “ );
eid = ei ;
ename = en ;
esal = es ;
System.out.println(“eid = “ + eid );
System.out.println(“ename = “ + ename );
System.out.println(“esal = “ + esal );
} // show
} // person class
class Demo        // class with main section
{
public static void main ( String args[ ] )
{
Person obj = new Person ( ) ;   // object creation
obj.Person( ) ;
obj.show( 101 , “sai” , 15000.59f ) ;
boolean result = obj instance of Person ;
System.out.println ( “ Checking whether the obj is an instance of person or not “ );
System.out.println ( result );
Person obj1 = new Person ( ) ;     // multiple object creation
obj1.Person( ) ;
obj1.show( 102 , “ram” , 72000.68f ) ;
boolean result1 = obj1 instance of Person ;
System.out.println ( “ Checking whether the obj1 is an instance of person or not “ );
System.out.println ( result1 );
} // main method
} // demo class

Output:

eid = 0
ename = null
esal = 0.0f
Storing local variables into instance variables
eid = 101
ename = sai
esal = 15000.59
Checking whether the obj is an instance of person or not
true
eid = 0
ename = null
esal = 0.0f
Storing local variables into instance variables
eid = 102
ename = ram
esal = 72000.68
Checking whether the obj1 is an instance of person or not
true

Related Topics

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.