Java Class & Objects
Objects and classes are used to specify an object and combine data representation and methods for manipulating the data. The members of the class are also known as data and functions within the class.

Class
The class is a blueprint of an object. Collection of objects is known as class. It is a logical entity. It starts with the keyword followed by the class name and the class body.
Syntax:
class class_name { data_type instance_variable; type method_name(parameter_list); }
Object
The object in Java language matches a real-world entity. Objects having state and behavior. In Java language class provide the blueprint of an object, so basically, an object is created from a class.
The new operator is used to create a heap memory space for the class object.
Syntax:
class_name objectname= new class_name();

Defining the Object of a Class
An object is an instance of a class. A class must be defined pior to the object declaration. A class provides a template, which defines the methods and variables that are required for objects of the class type.
Syntax:
class class_name { <access specifier>:data_type instance_variable; type method_name(parameter_list); } class_name object= new class_name();
Access Specifiers
Specifiers | Private | Default | Protected | Public |
---|---|---|---|---|
Within Same class | Yes | Yes | Yes | Yes |
Same Package Derived Class | No | Yes | Yes | Yes |
Same Package non-derived Class | No | Yes | Yes | Yes |
Different Package Derived Class | No | No | Yes | Yes |
Different Package non-derived Class | No | No | No | Yes |
Accessing Class Members
The data members or methods of a class construct is accessed using the . operator.
Example 1:
class Rectangle { int length,breadth; float area; } public class Oops { public static void main(String args[]){ // r1 is the object created for the class Rectangle Rectangle r1=new Rectangle(); r1.length=5; r1.breadth=6; System.out.println("Enter the length and breadth value: "+r1.length+" "+r1.breadth); r1.area = r1.length * r1.breadth; System.out.println("Area of the Rectangle: "+r1.area); } }
Example 2:
class Rectangle { int length,breadth; float area; void get_data(int l, int b) { length=l; breadth=b; area= length * breadth; } void show_data() { System.out.println("Enter the length and breadth value: "+length+" "+breadth); System.out.println("Area of the Rectangle: "+area); } } public class Oops1 { public static void main(String args[]) { Rectangle r1=new Rectangle(); r1.get_data(5,6); r1.show_data(); } }
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.