Classes and Objects in Java
Last Updated :
12 Aug, 2024
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.
In this article, we will discuss Java objects and classes and how to implement them in our program.
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student named Ravi is an object.
Properties of Java Classes
- Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
- Class does not occupy memory.
- Class is a group of variables of different data types and a group of methods.
- 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 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);
}
}
Java
// Java program to Illustrate Creation of Object
// Using new Instance
// Main class
class GFG {
// Declaring and initializing string
String name = "GeeksForGeeks";
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
Class cls = Class.forName("GFG");
// Creating object of main class
// using instance method
GFG obj = (GFG)cls.newInstance();
// Print and display