Classes
The class is at a core of Java. It is a logical construct upon which the entire Java language is built. It defines the shape and nature of an object. A class forms the basis of OOP’s in Java. It provides you to Encapsulate data and code into a single unit. Once a class has been created, you can create as many objects as you want for the class. Infect objects are variables of the type ‘ class’.
Syntax:
- class class_name
- {
- data type inst_var-1:
- data type inst_var-2:
- …………………….
- return_type Method_name1([args])
- {
- ………………..
- }
- return_type Method_name2([args])
- {
- ………………….
- }
- …………………….
- }
- class Box
- {
- double height;
- double width;
- double depth;
- }
| Note: class : A reserved keyword, which allows you to, builds a class and which defines the shape and nature of the object. class_name : Specifies a name given to the entire design. data_type instance variable : Referred as data members. Method_name : Pieces of codes that manipulate the instance variables commonly referred as methods or member methods. |
Collectively the instance variables and member methods are called the members of the class.
Creating objects:
- A class just provides you with a template. Once a class has been created the next step would create variables of type “class”. Objects can be created in the following format
Syntax: class_name object_name = new class_name();
- Where class_name is the name of the class.
- Where object_name is the name of the object.
- Where new is the dynamic memory allocator.
- Where class_name() is the default constructor.
Example: Box B = new Box();
- Once an object has been created, you can access the instance variables of the object using the notation.
Syntax: Object_name.instance_variable
Example:
- B.width;
- B.height;
- B.depth;
class Box{
}class App14{
} |
- output:
- \>javac App14.java
- \>java App14
- The volume of the box is : 6000.0
Accessing Methods of an object:
- Just like you access the instance variables. You can also access methods from outside the class using the following notation.
Syntax: object_name.method_name([arguments]);
