1

In my program I have class Vehicle and class Car which inherit from Vehicle. I've created two Car's objects c and c2. Now I have to make sumFuel() method in Calculate class which sums fuel used by Car's objects.

c.fuel+ c2.fuel; It works when I write it in main, but how can I do this in class method? I'm also considering doing array of Car's objects, but I don't know where I should place it and how to refer to it in sumFuel().

package javaapplication25;


public class JavaAplication25 {

    public static void main(String[] args) {
       
       Car c= new Car();
       Car c2= new Car();
       
       c.setVehicle(200,5547,50);
       c.display();
       
       c2.setVehicle(150,5087,100);
       c2.display();
        
        
        
    }
    
}
class Vehicle
{
    int speed;
    int nr;
   
    void setVehicle(int speed, int nr)
    {
        this.speed=speed;
        this.nr=nr;
    }
    void display()
    {
         System.out.println("Speed: "+speed );
         System.out.println("Nr: "+nr);
         
    }

}
class Car extends Vehicle
{
   int fuel;
   void setVehicle(int speed, int nr, int fuel)
   {
          
  
         super.setVehicle(speed, nr);
         this.fuel=fuel;
         
   }
   void display()
   {
       super.display();
       System.out.println("Fuel: "+ fuel);
   }
   
}
class Calculate extends Car
{
   int sum=0; 
   /*int sumFuel()
   {
       
      
   }*/
}
4
  • 3
    Why is Calculate extending Car? Commented Mar 25, 2018 at 18:38
  • In Car I've declared variable fuel, so I want to access it in Calculate.. Commented Mar 25, 2018 at 18:43
  • You do not need to extend class Car to be able to access fuel. General pattern is to make the fields private and create a getter which exposes it. So it looks like int getFuel() { return fuel; } and latter in code you can call it c1.getFuel(). Then if you want to sum the fuels of all cars, you use this accessor method. Consider having List<Cars> cars you can sum their fuel in this way: int fuel = cars.stream().mapToInt(Car::getFuel).sum() Commented Mar 25, 2018 at 18:47
  • @MichalLonski please add your comment as an answer. Its good. Probably add advice on how the Calculate.sumFuel method would call method getFuel Commented Mar 25, 2018 at 18:56

3 Answers 3

1

You do not need to extend class Car to be able to access fuel (the Calculation class). General pattern is to make the fields private and, if needed, create a getter which exposes it. So it looks like:

class Car {
  private int fuel;

  int getFuel() { 
    return fuel; 
  } 
}

and latter in code you can call it: c1.getFuel(). Then if you want to sum the fuels of all cars, you use this accessor method.

Consider having list of cars:

Car c1 = new Car();
c.setVehicle(200,5547,50);
Car c2 = new Car();
c2.setVehicle(150,5087,100);

int fuelSum = Stream.of(c1, c2).mapToInt(Car::getFuel).sum();

Or in more ancient way:

List<Car> cars = Arrays.asList(c1, c2);
int sum = 0;
for(Car car : cars)
  sum += car.getFuel();

Additionaly instead of having method setVehicle I would create a constructor:

class Car {
  Car(int speed, int nr, int fuel) {
    //... 
  }
}

If you really want to wrap this in the Calculation class, it might look like this:

class Calculation {
  int calculateFuel(List<Cars> cars) {
    return cars.stream().mapToInt(Car::getFuel).sum()
  }
}

and usage in main (with constructor instead of setVehicle method):

Car c1 = new Car(200,5547,50);
Car c2 = new Car(150,5087,100);
Calculation clac = new Calculation();
int fuelSum = calc.calculateFuel(Arrays.asList(c1, c2));

Also since it does not require any state, it might be a static method (static int calculateFuel(List<Cars> cars)), and you will not need to create an instance of calculation class:

//Calculation clac = new Calculation() - not needed
int fuelSum = Calculation.calculateFuel(Arrays.asList(c1, c2));

And one more thing - you created methods display. It is ok, but there is a method toString() on the Object class which you can override instead of creating new one:

class Car {
  // (...)
  @Override
  public String toString() {
      System.out.println("Speed: "+speed );
      System.out.println("Nr: "+nr);
  }
}

The adventage is that it is automatically called when you will put in into a printing method such as below one:

Car c1 = new Car(200,5547,50);
System.out.println(c1); //automatically called c1.toString() here
Sign up to request clarification or add additional context in comments.

Comments

0

The code snippet says you are a novice in java: Try to understand the uses of private, public and protected access modifiers and how to use constructors to instantiate the object with some data.

Coming back to your question just try this:

public class JavaAplication25 {

public static void main(String[] args) {

    Car c = new Car(200,5547,50);
    Car c2 = new Car(150,5087,100);

    c.display();
    c2.display();

    Car cars[] = {c,c2}; //array of cars
    Calculate calculateFuel = new Calculate();
    System.out.println("Total fuel:" + calculateFuel.sumFuel(cars));
}

private static class Vehicle {
    private int speed;
    private int nr;

    Vehicle(int speed, int nr) {
        this.speed=speed;
        this.nr=nr;
    }
    protected void display() {
        System.out.println("Speed: "+speed );
        System.out.println("Nr: "+nr);
    }
}

private static class Car extends Vehicle {
    private int fuel;

    Car(int speed, int nr, int fuel) {
        super(speed, nr);
        this.fuel=fuel;
    }

    protected void display() {
        super.display();
        System.out.println("Fuel: "+ fuel);
    }

}

private static class Calculate {
    private int sum = 0;

    private int sumFuel(Car arrayOfCars[]) {
        for (int i=0; i<arrayOfCars.length; i++) {
            sum = sum + arrayOfCars[i].fuel;
        }
        return sum;
    }
}
}

Don't just try to get the solution to this question but also try to understand the access modifiers and constructors.

Comments

0

As I see you are very beginer at Java. To solve your problem you can make static method which can be called without creating object:

public class Calculator {
public void static calculate(int fuel1, int fuel2) {
System.out.println(fuel1 + fuel2);
}   
}

I recommend you at first read some book about java basics because code which you posted is very very bad. :(

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.