Class
Any concept that we want to implement in oop’s must be encapsulated within a class. A class is a template for an object and an object is an instance for a class.
In another words class is a user defined data type.
Object
An object is a
It is a basic unit of Object Oriented Programming and represents the real-life entities. In a java program, we can create many
How to create object
Syntex for object:
1 | ClassName ObjectName = new ClassName(); |
new operator dynamically allocates memory for an object
Write a program to demonstrate class and variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class RectangleArea { int length; int width; } public class Area { public static void main(String arg[]) { RectangleArea obj1 = new RectangleArea(); RectangleArea obj2 = new RectangleArea(); int a; // assign value to obj1 instance variable obj1.length = 10; obj1.width = 20; // assign value to obj2 instance variable obj2.length = 10; obj2.width = 30; a = obj1.length * obj1.width; System.out.println("Area of the rectangle =" + a); a = obj2.length * obj2.width; System.out.println("Area of the rectangle =" + a); } } |
Result
1 2 | Area of the rectangle =200 Area of the rectangle =300 |
In
1 2 3 | RectangleArea obj1; obj1 = new RectangleArea (); |
Next line allocates a