Java Classes and Objects

Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.


Class

A class is a user defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:

  1. Modifiers : A class can be public or has default access (Refer this for details).
  2. Class name: The name should begin with a initial letter (capitalized by convention).
  3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  5. Body: The class body surrounded by braces, { }.

Object

It is a basic unit of Object Oriented Programming and represents the real life entities.  A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :

  1. State : It is represented by attributes of an object. It also reflects the properties of an object.
  2. Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects.
  3. Identity : It gives a unique name to an object and enables one object to interact with other objects.

Understanding how to initialize an object with a programming example:

// Class Declaration
  
public class Car
{
    // Instance Variables
    String brand;
    String model;
    int price;
  
    // Constructor Declaration of Class
    public Dog(String brand, String model,
                   int price)
    {
        this.brand = brand;
        this.model = model;
        this.price = price;
    }
  
    // method 1
    public String getBrand()
    {
        return brand;
    }
  
    // method 2
    public String getModel()
    {
        return model;
    }
  
    // method 3
    public int getPrice()
    {
        return price;
    }
  
  
    @Override
    public String toString()
    {
        return("Car's brand is "+ this.getBrand()+
               ".\nModel and Price is " +
               this.getModel()+"," + this.getPrice());
    }
  
    public static void main(String[] args)
    {
        Car example = new Car("Honda","City", 12);
        System.out.println(example.toString());
    }
}


Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. 

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java