Java class explanation for Beginners

Java class and object are vital to understanding polymorphism, inheritance, method overloading, etc.

What is Class?

A class is a blueprint for any functional entity. Which defines its properties and function. It defines a new data type. This new type can be used to create objects of that type. Class is a template for an object and an object is an instance of class.

The General form of Java class:

A class is declared by the “class “keyword. When you define a class, you declare its exact form and nature. Inside the Java class, you specify the data that it contains and code that operates on that data. A class code defines the interface to its data.

>General form of Java class Program:

class class_name {
type instance_variable1;
type instance_variable2;
type methodname1(parameter_list) {
// body of method
}
}

The variables, data defined in a class called instance variables. The code is contained within methods. The methods and variables defined within a class are called members of the class.
Each object of the class contains its own copy of these variables. The data for one object is unique from other data.

Java Syntax Explanation CLICK HERE

Java objects explanation:

When you create a Java class, you are creating a new data type. It has two steps to create an object.

STEP 1:Declare a variable of the class type.

Syntax:


class_name object_name;//declare reference to object

STEP2: Acquire an actual, physical copy of the object and assign it to that variable.

In the below sample syntax is used to declare an object of type name Sample:

class_name object_name = new constructor_name(); //allocate a object

How new operator works?

The first step declares a reference to an object. In the first step, it doesn’t refer to an actual object. The second step builds a physical copy of the object.”class_name “is the name of the class.“constructor_name” is the constructor of the class.

new keyword allocates memory for an object during run time. Then the program can create as many or as few objects as it needs during the execution of your program.

//This program declares one Rectangle object 
class Rectangle {
double length;
double breadth;
double height;
}
class Demo {
public static void main(String args[]) {
Rectangle obj; //declare reference to object
Rectangle obj = new Rectangle(); //allocate a object
double vol;
Rectangle.length = 10;
Rectangle.breadth = 20;
Rectangle.height = 30;
vol = Rectangle.length * Rectangle.breadth * Rectangle.height;
System.out.println("Volume of Rectangle");
System.out.println("volume is " +vol);
} }

OUTPUT:

Volume of Rectangle 
volume is 6000.0

Leave a comment