Class and Objects in Java


Class in Java

☞Class is a blueprint or template for its objects.

☞It is a description of object’s property(characteristics) and behavior.

☞It is a logical entity and cannot be physical.

Example

class Square{
    
    int side;
    
    void input(int s){
        side=s;
    }
    
    void area() {
        System.out.println("Area is "+(side*side));
    }
    
    void perimeter() {
        System.out.println("Perimeter is "+(4*side));
    }

}
Note: Class Square will not get a memory by doing this until you create an object.

Objects in Java

☞Object is a real world entity.

☞It is an instance (example) of a class.

☞It consumes memory to hold property values.

☞An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical.

☞Creating an object: use new keyword

Square s1=new Square();

Example

class Square{
    
    int side;
    
    void input(int s){
        side=s;
    }
    
    void area() {
        System.out.println("Area is "+(side*side));
    }
    
    void perimeter() {
        System.out.println("Perimeter is "+(4*side));
    }
    
    public static void main(String[] args) {
        //creating an object
        Square obj= new Square();
        
        obj.input(5);
        obj.area();
        obj.perimeter();
    }
    
}

Output

Area is 25
Perimeter is 20
Note :
1. s1 is a reference variable that will store the address of an object.
2. s1 name will be used as an object name.