Full width home advertisement

Post Page Advertisement [Top]

How to create object in Java & what its benifit.

As i said in early lesson that objects is a instance of a class. Each instance have its own unique attribute.

In this lesson we make two classes. First for the main method and another for a object car.
Car have the following property:
Its name in string. Example: "Alto", "Scorpio", " Tavera", "Audi" etc.....
Its fuel in double. Example: 34.4 , 12.0. 839.343 etc....
Its fuelLimit in double. Example 100.00 etc...

It have one method which give the available fuel in that car.


Let's begin.



class ObjectTest
{
      public static void main(String args[])
     {
         Car myCar=new Car();
         myCar.fuel = 25;
         myCar.carName = "Audi";
         myCar.getFuel();
          
     }


}

class Car
{
     double fuel;
     double fuelLimit;
     String carName;

     public void getFuel()
    {
         System.out.println("Your car fuel is: " + fuel);
    }
 
}

Here fuel, fuelLimit, carName, are the variables which can store different values.

 In System.out.println("Your car fuel is: " + fuel), fuel is the variable define in class Car. Two or more string or variable or mix of it can be added by using plus sign.

Prev:  Classes, objects and instance

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib