OOP Concept: Class & Object

Class : A class is a template or blueprint for creating new type objects.

Object: An object exhibits the properties and behaviours defined by its class.

Take the example of Vehicle. Vehicle is a thing used for transporting people or goods. Then we have different types of vehicle: car, lorry, bicycle etc. Here vehicle is a class and car, lorry, bicycle are the objects.

vehiclesNow lets see the vehicle class:


public class Vehicle {
  private String type;
  private int numberOfWheels;

  Vehicle(String type, int numberOfWheels){    
     this.type = type;
     this.numberOfWheels = numberOfWheels;
  }
  
  public void look(){
     System.out.println("Type: "+ this.type);
     System.out.println("Number of wheels: "+ this.numberOfWheels);
  }

  public void start(){
     System.out.println("My " + this.type + " starts.");
  }

  public void run(){
     System.out.println("My " + this.type + " is running.");
  }
  
  public void stop(){
     System.out.println("My " + this.type + " stops.");
  }
}

Now lets create some objects like car, bicycle:


public class VehicleTest {
   public static void main(String[] args){
      Vehicle car = new Vehicle("car", 4);
      car.look();
      car.start();
      car.run();
      car.stop();

      Vehicle bicycle = new Vehicle("bicycle", 2);
      bicycle.look();
      bicycle.start();
      bicycle.run();
      bicycle.stop();
   }
}

Class Object

Here the properties of the objects (car, bicycle) are type and numberOfWheels. They are also called attributes and are defined by fields in Java.

A field in a class is a variable which can store a value that represents a particular property of an object.

The behaviours of an object of a class are also known as operations, and are defined using methods in Java.

In our case, the behaviours of the objects car and bicycle are defined using methods: look(), start(), run() and stop().

Fields and methods in a class declaration are collectively called members of the class.

Advertisements
OOP Concept: Class & Object

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s