You are on page 1of 1

DSA Tutorials ML & Data Science Web Development Practice Sign In

Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java Exception Handling Java Programs Java Project Java Collections Interview Java Intervie

Classes and Objects in Java


Classes and Objects in Java
Naming Conventions in Java
Recently Published
Read Courses Practice Video
Java Methods
In Java, classes and objects are basic concepts of Object Oriented Programming
Access Modifiers in Java
(OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior. For
Java Constructors
10 YouTube Channels That Top 15 Li
example, the animal type Dog is a class while a particular dog named Tommy is
Every So ware Developer Tricks Fo
Four Main Object Oriented an object of the Dog class. Should Follow
Programming Concepts of Java
In this article, we will discuss Java objects and classes and how to implement Read
Inheritance in Java them in our program.

Abstraction in Java Java Classes


A class in Java is a set of objects which shares common characteristics/ behavior
Encapsulation in Java
and common properties/ attributes. It is a user-defined blueprint or prototype
Polymorphism in Java from which objects are created. For example, Student is a class while a particular
We use cookies to ensure you have the best browsing experience
student named on Ravi
our website.
is an By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy
object. Got It !
Interfaces in Java Policy

Properties of Java Classes


'this' reference in Java

1. Class is not a real-world entity. It is just a template or blueprint or prototype


from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface

Class Declaration in Java

access_modifier class <class_name>


{
data member;
method;
constructor;
nested class;
interface;
}

Example of Java Class

Java Java Java

// Java Program for class example

class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;

public static void main(String args[])


{
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Output 1

0
null

Output 2

GeeksForGeeks

Output 3

GeeksForGeeks

Components of Java Classes

In general, class declarations can include these components, in order:

1. Modifiers: A class can be public or has default access (Refer this for
details).
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by
convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass)
one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented
by the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
6. Body: The class body is surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that
provide the state of the class and its objects, and methods are used to implement
the behavior of the class and its objects.
There are various types of classes that are used in real-time applications such
as nested classes, anonymous classes, and lambda expressions.

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents
real-life entities. Objects are the instances of a class that are created to use the
attributes and methods of a class. A typical Java program creates many objects,
which as you know, interact by invoking methods. An object consists of :

1. State: It is represented by attributes of an object. It also reflects the properties


of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.

Example of an object: dog

Java Objects

Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, and “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.

Note: When we create an object which is a non primitive data type, it’s
always allocated on the heap memory.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of
those attributes, i.e. the state are unique for each object. A single class may have
any number of instances.

Example:

Java Object Declaration

As we declare variables like (type name;). This notifies the compiler that we will
use the name to refer to data whose type is type. With a primitive variable, this
declaration also reserves the proper amount of memory for the variable. So for
reference variables , the type must be strictly a concrete class name. In general,
we can’t create objects of an abstract class or an interface.

Dog tuffy;

If we declare a reference variable(tuffy) like this, its value will be


undetermined(null) until an object is actually created and assigned to it. Simply
declaring a reference variable does not create an object.

Initializing a Java object

The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the
class constructor.

Example:

Java

// Class Declaration

public class Dog {


// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName() { return name; }

// method 2
public String getBreed() { return breed; }

// method 3
public int getAge() { return age; }

// method 4
public String getColor() { return color; }

@Override public String toString()


{
return ("Hi my name is " + this.getName()
+ ".\nMy breed,age and color are "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}

public static void main(String[] args)


{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

Output

Hi my name is tuffy.
My breed,age and color are papillon,5,white

Initialize by using method/function:

Java

public class GFG {


// sw=software
static String sw_name;
static float sw_price;

static void set(String n, float p)


{
sw_name = n;
sw_price = p;
}

static void get()


{
System.out.println("Software name is: " + sw_name);
System.out.println("Software price is: "
+ sw_price);
}

public static void main(String args[])


{
GFG.set("Visual studio", 0.0f);
GFG.get();
}
}

Output

Software name is: Visual studio


Software price is: 0.0

This class contains a single constructor. We can recognize a constructor because


its declaration uses the same name as the class and it has no return type. The
Java compiler differentiates the constructors based on the number and the type of
the arguments. The constructor in the Dog class takes four arguments. The
following statement provides “tuffy”, “papillon”,5, and “white” as values for those
arguments:

Dog tuffy = new Dog("tuffy","papillon",5, "white");

The result of executing this statement can be illustrated as :

Memory Allocation of Java Objects

Note: All classes have at least one constructor. If a class does not explicitly
declare any, the Java compiler automatically provides a no-argument
constructor, also called the default constructor. This default constructor
calls the class parent’s no-argument constructor (as it contains only one
statement i.e super();), or the Object class constructor if the class has no
other parent (as the Object class is the parent of all classes either directly
or indirectly).

Ways to Create an Object of a Class


There are four ways to create objects in Java. Strictly speaking, there is only one
way(by using a new keyword), and the rest internally use a new keyword.

1. Using new keyword

It is the most common and general way to create an object in Java.

Example:

// creating object of class Test


Test t = new Test();

2. Using Class.forName(String className) method

There is a pre-defined class in java.lang package with name Class. The


forName(String className) method returns the Class object associated with the
class with the given string name. We have to give a fully qualified name for a
class. On calling the new Instance() method on this Class object returns a new
instance of the class with the given string name.

// creating object of public class Test


// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

3. Using clone() method

clone() method is present in the Object class. It creates and returns a copy of the
object.

// creating object of class Test


Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();

4. Deserialization

De-serialization is a technique of reading an object from the saved state in a file.


Refer to Serialization/De-Serialization in Java

FileInputStream file = new FileInputStream(filename);


ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

In real-time, we need different objects of a class in different methods. Creating a


number of references for storing them is not a good practice and therefore we
declare a static reference variable and use it whenever required. In this case, the
wastage of memory is less. The objects that are not referenced anymore will be
destroyed by the Garbage Collector of Java.

Example:

Test test = new Test();


test = new Test();

In the inheritance system, we use a parent class reference variable to store a sub-
class object. In this case, we can switch into different subclass objects using the
same referenced variable.

Example:

class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Test
{
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}

Anonymous Objects in Java


Anonymous objects are objects that are instantiated but are not stored in a
reference variable.

They are used for immediate method calls.


They will be destroyed after method calling.
They are widely used in different libraries. For example, in AWT libraries, they
are used to perform some action on capturing an event(eg a key press).
In the example below, when a key button(referred to by the btn) is pressed,
we are simply creating an anonymous object of EventHandler class for just
calling the handle method.

btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});

Difference between Java Class and Objects


The differences between class and object in Java are as follows:

Class Object

Class is the blueprint of an object. It is


An object is an instance of the class.
used to create objects.

No memory is allocated when a class Memory is allocated as soon as an


is declared. object is created.

An object is a real-world entity such as


A class is a group of similar objects.
a book, car, etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as


A class can only be declared once.
per requirement.

Objects of the class car can be BMW,


An example of class can be a car.
Mercedes, Ferrari, etc.

Last Updated : 22 Sep, 2023 578

Previous Next

Why Java is not a purely Object- Naming Conventions in Java


Oriented Language?

Share your thoughts in the comments Add Your Comment

Similar Reads
Understanding Classes and Objects in
Java.util.Objects class in Java
Java

Catching Base and Derived Classes as equals() on String and StringBu er


Exceptions in C++ and Java objects in Java

Di erence Between Equality of Objects


Passing and Returning Objects in Java
and Equality of References in Java

Sorting Elements of Arrays and Wrapper Commonly Used Methods in LocalDate,


Classes that Already Implements LocalTime and LocalDateTime Classes in
Comparable in Java Java

Private Constructors and Singleton Parent and Child Classes Having Same
Classes in Java Data Member in Java

Complete Tutorials

Coding For Kids - Online Free Tutorial to


Java AWT Tutorial
Learn Coding

Computer Science and Programming


Spring MVC Tutorial
For Kids

Spring Tutorial

G Gaurav Miglani

Article Tags : java-basics , Java , School Programming

Practice Tags : Java

Additional Information

Company Explore Languages DSA Data Science & HTML & CSS

A-143, 9th Floor, Sovereign Corporate About Us Job-A-Thon Hiring Python Data Structures ML HTML
Tower, Sector-136, Noida, Uttar Pradesh - Challenge
Legal Java Algorithms Data Science With CSS
201305
Careers Hack-A-Thon C++ DSA for Beginners Python Bootstrap

In Media GfG Weekly Contest PHP Basic DSA Problems Data Science For Tailwind CSS
O line Classes Beginner
Contact Us GoLang DSA Roadmap SASS
(Delhi/NCR) Machine Learning
Advertise with us SQL Top 100 DSA LESS
DSA in JAVA/C++ Tutorial
GFG Corporate R Language Interview Problems Web Design
Master System ML Maths
Solution Android Tutorial DSA Roadmap by
Design Sandeep Jain Data Visualisation
Placement Training Tutorials Archive
Master CP Tutorial
Program All Cheat Sheets
GeeksforGeeks Pandas Tutorial
Apply for Mentor
Videos NumPy Tutorial

NLP Tutorial

Deep Learning
Tutorial

Python Computer DevOps Competitive System Design JavaScript

Python Science Git Programming What is System TypeScript


Programming GATE CS Notes AWS Top DS or Algo for Design ReactJS
Examples CP Monolithic and
Operating Systems Docker NextJS
Django Tutorial Top 50 Tree Distributed SD
Computer Network Kubernetes AngularJS
Python Projects Top 50 Graph High Level Design or
Database Azure NodeJS
Python Tkinter HLD
Management GCP Top 50 Array Express.js
Web Scraping System Low Level Design or
DevOps Roadmap Top 50 String Lodash
LLD
OpenCV Python So ware Top 50 DP
Crack System Design Web Browser
Tutorial Engineering
Top 15 Websites for Round
Python Interview Digital Logic Design CP
Question System Design
Engineering Maths
Interview Questions

Grokking Modern
System Design

NCERT School Subjects Commerce Management & UPSC Study SSC/ BANKING
Solutions Mathematics Accountancy Finance Material SSC CGL Syllabus

Class 12 Physics Business Studies Management Polity Notes SBI PO Syllabus

Class 11 Chemistry Indian Economics HR Managament Geography Notes SBI Clerk Syllabus

Class 10 Biology Macroeconomics Income Tax History Notes IBPS PO Syllabus

Class 9 Social Science Microeconimics Finance Science and IBPS Clerk Syllabus

Class 8 English Grammar Statistics for Economics Technology Notes SSC CGL Practice

Complete Study Economics Economy Notes Papers

Material Ethics Notes

Previous Year Papers

Colleges Companies Preparation Exams More Tutorials Write & Earn

Indian Colleges IT Companies Corner JEE Mains So ware Write an Article


Admission & So ware Company Wise JEE Advanced Development Improve an Article
Campus Experiences Development Preparation So ware Testing
GATE CS Pick Topics to Write
Top Engineering Companies Preparation for SDE Product
NEET Share your
Colleges Artificial Management
Experienced UGC NET Experiences
Top BCA Colleges Intelligence(AI) Interviews SAP Internships
Top MBA Colleges Companies
Internship SEO
Top Architecture CyberSecurity Interviews Linux
College Companies
Competitive Excel
Choose College For Service Based Programming
Graduation Companies
Aptitude
Product Based Preparation
Companies
Puzzles
PSUs for CS
Engineers

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like