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()
{
}*/
}
Carto be able to accessfuel. General pattern is to make the fields private and create a getter which exposes it. So it looks likeint getFuel() { return fuel; }and latter in code you can call itc1.getFuel(). Then if you want to sum the fuels of all cars, you use this accessor method. Consider havingList<Cars> carsyou can sum their fuel in this way:int fuel = cars.stream().mapToInt(Car::getFuel).sum()getFuel