Wednesday 6 April 2016

Class in java

Think of java without a class...
It's not possible.
Java begins with a class.

Class is generally considered as the blueprint/template that describes the state/behavior that object of its type support.
This is definition which one can find in any book or tutorial. But what does it actually mean?

Why a class can be considered as a blueprint/template?

Lets try to find out taking real life example.
If we look on the road, we can see different type of cars, buses running here and there.Each of these can be
considered as an instance of a class Vehicle. And these instances are born from the same set of blueprints and thus consists of same components.
Lets take a look :

public class Vehicle {
       int maxSpeed;
       String model;
       int seats;
       int price_per_seat;
      
       public int fareCollection(int seat, int price_per_seat){
              int totalFare = seat*price_per_seat;
              return totalFare;
       }
      
       public void acceleration(){
              //create logic to calculate acceleration which
              //instance of vehicle will use
       }

}



public class VehicleType {

       public static void main(String[] args) {
              Vehicle car = new Vehicle();     //creating car from vehicle blueprint
              car.model = "car1190";
              car.seats = 6;
              car.maxSpeed = 150;
              car.price_per_seat = 50;
              int total_car_fare = car.fareCollection(car.seats, car.price_per_seat);
             
              System.out.println("Total collection of car model "+ car.model +" per trip : "+ total_car_fare);
             
              Vehicle bus = new Vehicle();     //creating bus from vehicle blueprint
              bus.model = "bus123";
              bus.seats = 45;
              bus.maxSpeed = 60;
              bus.price_per_seat = 10;
              int total_bus_fare = bus.fareCollection(bus.seats, bus.price_per_seat);
              System.out.println("Total collection of bus model "+ bus.model +" per trip : "+ total_bus_fare);

       }

}

You can see here, how the two different instance use same template Vehicle but yet have different state and behavior.
The fields maxSpeed, model, 
seats, price_per_seat represents object state and methods  fareCollection() and acceleration()  define behavior and the way individual object interacts with outside world.


*Depending on the state of each instance the behavior changes.

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.