Classes and Objects in Java
Classes and Objects in Java
Classes and objects in Java make it an object-oriented programming(OOP) language. Everything in Java is linked with classes and objects.
What is a Class in Java?
A class is a template of an object. It represents a real-life entity and describes what an object does and how along with its properties. It consists of data members and member functions which specify properties and methods that work on those properties respectively. It is a user-defined data type and is not allocated memory when created.
How is a Class created in Java?
The class keyword is used to create a class. Class creation starts with the keyword followed by class name and a pair of curly braces. Its methods and attributes are placed inside these braces.
Syntax of Class Creation:
class ClassName{ access_specifier attribute; access_specifier method; }
access_specifier:
It specifies the access modifier of the members of the class which defines their visibility. They are of 4 types:
-
-
public
-
private
-
protected
-
default -> when no access_specifier is mentioned
-
Access Specifier | Class | Package | Sub-Class | Application |
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes | No |
default | Yes | Yes | No | No |
private | Yes | No | No | No |
What is an Object in Java?
An object is an instance of a class. Every object has its own copy of data members and member functions of the class except for the static members which are shared by them. Memory is assigned to an object when created and not the class which describes what and how tasks will be done.
How is an Object created in Java?
In Java, the object is created using a new keyword and is assigned to a variable which is the name of the object. To access members of a class for a particular object, dot operator(.) is used.
Syntax of Object Creation:
class_name object_name=new class_name(); object_name.attribute_name; object_name.method_name(parameter_list);
How to create Classes and Objects in Java with Example:
//Java Program with object public class MyClass { //class data member int var=10; public static void main(String[] args) { MyClass obj=new MyClass(); //accessing data member through object using dot operator System.out.println(obj.var); } }
Output:
10
Difference between Classes and Objects in Java
Classes | Objects |
It is a code template that defines what and how tasks will be done. | It is defined as an instance of a class. |
No memory is allocated to it. | Memory is allocated to it. |
It is a data type. | It is not a data type. |