I just need some assistance in stopping the print method. its printing my output twice as car1.print(); car2.print(); is in the print method at the bottom. how do i exclude this without deleting it. It has to be put in the super.print() part.
class Vehicle { // base class
int capacity;
String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
super.print();
{
System.out.println(" type = " + theType);
System.out.println(" Model = " + theModel);
}
}
}
class Task1 {
public static void main(String[] args) {
Car car1 = new Car(1200,"Holden","sedan","Barina");
Car car2 = new Car(1500,"Mazda","sedan","323");
car1.print();
car2.print();
}
}
You can use the super keyword in the constructor to invoke the super class' constructor and pass parameters to it.
Note that it must be the first statement in the constructor:
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake); // Here
type = theType;
model = theModel;
}
}
You are missing the Constructor
public Car (int theCapacity, String theMake, String theType, String theModel) {
capacity = theCapacity;
make = theMake;
Type = theType;
Model = theModel;
}
or
public Car (int theCapacity, String theMake, String theType, String theModel) {
super (theCapacity, theMake);
Type = theType;
Model = theModel;
}
You have to call super constructor by passing simply parameters in child class.
public Car(int capacity, String make, String type, String model) {
super(capacity, make); // simply call super
this.type = type;
this.model = model;
}
One of the solution is calling your base class Constructor from child class using super keyword and adding other parameters from child class constructor as mentioned by #Mureinik
Depending on the requirements of the Base Class you can also try using abstract methods. Example code is below.
abstract class Vehicle {
static int capacity;
static String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
protected static void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
// you can use these methods where you want in this base class.
System.out.println(" type = " + getType());
System.out.println(" model = " + getModel());
}
protected abstract String getType();
protected abstract String getModel();
}
public class Car extends Vehicle{
Car(int theCapacity, String theMake) {
super(theCapacity, theMake);
}
/**
* #param args
*/
public static void main(){
print();
}
#Override
protected String getType() {
// TODO Auto-generated method stub
return "Audi";
}
#Override
protected String getModel() {
// TODO Auto-generated method stub
return "Q7";
}
}
Related
I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());
This question was asked in my recent coding round. Its kind of tricky as we cannot modify getClass() and getClass().getName()
along with main method, Given are Food and FoodFactory class templates.
I had to print the following lines:
My name is Fastfood.
My name is Fruits.
Our superclass is Food
I'm serving Fastfood
I'm serving Fruit
Code:
/* Name of the class has to be "Main" only if the class is public. */
class FoodFactory{
public Food getFood(String string) {
// TODO Auto-generated method stub
return new Food(string);
}
public String toString(){
return "Food";
}
public static String getName(){
return "Food";
}
}
class Food{
String name;
public Food(String string) {
this.name = string;
}
public void servesFood() {
System.out.println("I'm serving "+name);
}
public String getName(){
return name;
}
}
class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
foodFactory myFoods = new foodFactory();
Food food1 = myFoods.getFood("Fastfood");
Food food2 = myFoods.getFood("Fruits");
System.out.println("My name is: " + food1.getClass().getName());
System.out.println("My name is: " + food2.getClass().getName());
System.out.println("Our superclass is: " + food1.getClass().getSuperclass().getName());
food1.servesFood();
food2.servesFood();
}
}
The key thing for this exercise is revealed by one word in your example output: superclass.
You want that getClass().getName() gives you different output. In order to get there, surprise: the objects you call getClass().getName() on ... need to have different classes!
Something like
class Food {
public void servesFood(){
System.out.println("I'm serving Food");
}
}
class FastFood extends Food {
#Override
public void servesFood(){
System.out.println("I'm serving Fastfood");
}
... similar for Fruit
If you now create instances of those two objects, they will give you the expected output. Now the question is: how are instances created?!
That is where your factory comes in:
class FoodFactory {
public Food getFood(String name) {
switch(name) {
case "FastFood" : return new Fastfood();
case "Fruit" : return new Fruit();
default: return new Food();
}
}
Please note: the above implementation assumes that any food that is not "Fastfood" or "Fruit"... is real "Food". And of course: you might expect that the actual "name" of the fruit ends up as some field within your Food class, but such refinements/extensions are left as exercise to the reader.
Here are the implementations of the two classes.
class FoodFactory{
private String name;
public Food getFood(String name){
this.name = name;
Food food = new Food(name);
return food;
}
public String getName{
return name;
}
}
class Food extends FoodFactory{
private String name;
public Food(String name){
this.name = name;
}
public void servesFood(){
System.out.println("I'm serving "+ name);
}
public String getName(){
return name;
}
}
This should work.
This one will work.
class FoodFactory extends Food {
public Food getFood(String string) {
if (string.equals("Fruit")) {
return new Fruit("Fruit");
} else {
return new FastFood("FastFood");
}
}
}
class Fruit extends Food {
public Fruit(String name1) {
super.name = name1;
}
}
class FastFood extends Food {
public FastFood(String name1) {
super.name = name1;
}
}
class Food {
public String name = null;
public Food() {
}
public Food(String string) {
this.name = string;
}
public void servesFood() {
System.out.println("I'm serving " + this.name);
}
}
class Solution1 {
public static void main(String[] args) throws java.lang.Exception {
FoodFactory myFoods = new FoodFactory();
Food food1 = myFoods.getFood("FastFood");
Food food2 = myFoods.getFood("Fruit");
System.out.println("My name is: " + food1.getClass().getName());
System.out.println("My name is: " + food2.getClass().getName());
System.out.println("Our superclass is: "
+ food1.getClass().getSuperclass().getName());// modification
food1.servesFood();
food2.servesFood();
}
}
I'm working on a task which has the following classes:
Vehicle.java ( Abstract Class)
NewVehicle.java subClass of Vehicle.java
UsedVehicle.java subClass of Vehicle.java
VehicleParser.java used as a parser
Drive Class which is used as main
In the VehicleParser class I determine which object it is. Either it is a NewVehicle object or a UsedVehicle. And in the Drive class I fill an ArrayList with the Vehicle objects.
Now When I'm trying to System.out.println an Arraylist the drive class is just invoking toString method declared in UsedVehicle/NewVehicle but not invoking the method declared in the Vehicle.java class. I need it to first invoke the method toString of Vehicle and then concat the toString of UsedVehicle/NewVehicle with it.
Here is the Code:
Vehicle
public abstract class Vehicle {
protected String make;
protected int modelYear;
protected String motivePower;
protected double licenseFee;
public Vehicle(String make,int modeYear,String motivePower) {
this.make = make;
this.modelYear= modeYear;
this.motivePower = motivePower;
this.licenseFee = 0.0;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public int getModelYear() {
return modelYear;
}
public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}
public String getMotivePower() {
return motivePower;
}
public void setMotivePower(String motivePower) {
this.motivePower = motivePower;
}
public double getLicenseFee() {
return licenseFee;
}
public void setLicenseFee(double licenseFee) {
this.licenseFee = licenseFee;
}
public abstract void computeLicenseFee();
public String toString()
{
return "\nMake:\t\t"+getMake()+
"\nModel Year:\t"+getModelYear()+
"\n Motive Power:\t"+getMotivePower()+
"\nLicense Fee:\t"+getLicenseFee();
}
public static class UsedVehicle extends Vehicle
{
public String previousLicenseState;
public int currentYear;
int yearsOld = 0;
public UsedVehicle(String make, int modelYear, String power, String previousState, int currentYear)
{
super(make,modelYear,power);
this.previousLicenseState = previousState;
this.currentYear = currentYear;
}
public String getPreviousLicenseState() {
return previousLicenseState;
}
public void setPreviousLicenseState(String previousLicenseState) {
this.previousLicenseState = previousLicenseState;
}
public int getCurrentYear() {
return currentYear;
}
public void setCurrentYear(int currentYear) {
this.currentYear = currentYear;
}
public void computeLicenseFee() {
double baseFee = 100.00;
double titleTransferFee = 15.00;
double smogWaiverFee = 0.00;
double smogAbatement = 0.00;
yearsOld = getCurrentYear() - getModelYear();
if(yearsOld > 5)
{
smogWaiverFee = 8.00;
}
if("gas".equalsIgnoreCase(getMotivePower()))
{
smogAbatement = 20.00;
}
licenseFee = baseFee + smogAbatement + titleTransferFee + smogWaiverFee;
}
public String toString()
{
return "\n Years Old:\t"+yearsOld+
"\n Previous State:\t"+getPreviousLicenseState();
}
}
public static class NewVehicle extends Vehicle
{
public double vehiclePrice;
public NewVehicle(String make, int modeYear, String motivePower,double price) {
super(make, modeYear, motivePower);
this.vehiclePrice = price;
}
public double getVehiclePrice() {
return vehiclePrice;
}
public void setVehiclePrice(double vehiclePrice) {
this.vehiclePrice = vehiclePrice;
}
public void computeLicenseFee() {
double baseFee = 150.00;
double smogAbatement = 0.00;
double priceFee = 0.00;
if("gas".equalsIgnoreCase(getMotivePower()))
{
smogAbatement = 20.0;
priceFee = getVehiclePrice()*0.15;
}
licenseFee = baseFee + smogAbatement + priceFee;
}
public String toString()
{
return "Price:\t\t$"+getVehiclePrice();
}
}
}
Parser
public class VehicleParser {
public static Vehicle parseStringToVehicle(String lineToParse)
{
Vehicle vehicleObj = null;
Vehicle.UsedVehicle usedVeh = new Vehicle.UsedVehicle(make, modelYear, power, previousState, currentYear);
return vehicleObj;
}
}
DriveClass
Vehicle obj = VehicleParser.parseStringToVehicle(inputInfo);
vehicleList.add(obj);
System.out.println(vehicleList.get(i));
You are overriding the toString() method. Java doesn't do any special magic here. If you want the super class' method to be called, you need to do so explicitly with the super keyword:
#Override
public String toString()
{
return super.toString() + // Here
"\n Years Old:\t"+yearsOld+
"\n Previous State:\t"+getPreviousLicenseState();
}
Just consider this example:
public class A {
public String someMethod() {
return "A method";
}
}
public class B extends A {
#Override
public String someMethod() {
return "B method";
}
}
public class C extends B {
#Override
public String someMethod() {
return "C method";
}
}
Basically what's going on here is that when you inherit the parent class, you're overriding everything that's in parent class's method and you're giving new definition to it. By Overriding parent class's method, you're saying that:
I'm giving a new fresh definition to this method. From now onward, for all of my objects and my child's object, this is only going to be the definition that would be considered and any of parent's method definition is void.
Now if you want the parent's method definition to be called before calling this method definition, then you'd have to specifically state that using super.methodName() in your code.
public class A {
public String someMethod() {
return "A method";
}
}
public class B extends A {
#Override
public String someMethod() {
return super.someMethod() + "B method";
}
}
public class C extends B {
#Override
public String someMethod() {
return super.someMethod() + "C method";
}
}
When you call the subclass methods the overridden methods will be called and all the definitions in the parent's method will be overridden and you will get only the overridden method definition. So inprder to use the parents' method definition as well you need to use the super() method in your child class method...
return super.toString() + " is a new car!";
I'm having trouble printing out an array of StaffMember objects by utilizing the defined toString method with my driver. I keep getting a cannot find symbol error and I'm confused as to what I need to replace the staffList with in my driver to make things work out.
This is the part of the question I'm stuck on "Your program should first print all the staff members (use toString() method of the StaffMember class) to the terminal window"
Here is my code (the Staff and StaffMember classes are from the textbook and were not required to be changed for the assignment, so all problems are with my driver).
public class Staff
{
private StaffMember[] staffList;
public Staff ()
{
staffList = new StaffMember[6];
staffList[0] = new Executive ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 2423.07);
staffList[1] = new Employee ("Carla", "456 Off Line", "555-0101",
"987-65-4321", 1246.15);
staffList[2] = new Employee ("Woody", "789 Off Rocker", "555-0000",
"010-20-3040", 1169.23);
staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 10.55);
staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
"555-8374");
staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
"555-7282");
((Executive)staffList[0]).awardBonus (500.00);
((Hourly)staffList[3]).addHours (40);
}
public void payday ()
{
double amount;
for (int count=0; count < staffList.length; count++)
{
System.out.println (staffList[count]);
amount = staffList[count].pay();
if (amount == 0.0)
System.out.println ("Thanks!");
else
System.out.println ("Paid: " + amount);
System.out.println ("-----------------------------------");
}
}
}
This is the abstract class:
abstract public class StaffMember
{
protected String name;
protected String address;
protected String phone;
//-----------------------------------------------------------------
// Constructor: Sets up this staff member using the specified
// information.
//-----------------------------------------------------------------
public StaffMember (String eName, String eAddress, String ePhone)
{
name = eName;
address = eAddress;
phone = ePhone;
}
//-----------------------------------------------------------------
// Returns a string including the basic employee information.
//-----------------------------------------------------------------
public String toString()
{
String result = "Name: " + name + "\n";
result += "Address: " + address + "\n";
result += "Phone: " + phone;
return result;
}
//-----------------------------------------------------------------
// Derived classes must define the pay method for each type of
// employee.
//-----------------------------------------------------------------
public abstract double pay();
}
And this is what I've gotten for a driver so far:
import java.util.*;
public class EmployeeBinaryList
{
public static void main (String args[])
{
for (int i = 0; i < staffList.length; i++)
System.out.println(staffList[i].toString());
}
}
I've tried various things in place of the staffList and staffList[i], but I just can't seem to figure it out. Thanks a ton to anyone who can help me
you need to think about scope here. A variables scope is where that variable can be accessed. The easiest way to know the scope of a variable is by the curly braces. a variable is only accessible directly within the braces where it was defined. So, staffList is defined in the staff class, as such it is only accessible directly in the staff class.
you would have to access that variable through an object of the staff class:
System.out.println(StaffObject.StaffList) //StaffObject would be an object of the Staff class
however, in this case you also need to look at whether the variable is public or private. Private means it can not be accessed directly outside of its class. so in this case StaffObject.staffList would not be accessible outside of the Staff class
In order to access that StaffList variable you need what's called an Accessor method. A method which is public, and allows access to the variable for printing purposes.
so, here's whatcha gotta do:
First off you need an object of the staff class
Then, you need to use that object to access the appropriate Accessor method for printing
take a good look at the code, chances are its all there for a reason.
good luck!!
package com.cisco.staff;
public class Staff
{
private StaffMember[] staffList;
public Staff ()
{
staffList = new StaffMember[6];
staffList[0] = new Executive ("Sam", "123 Main Line",
"555-0469", "123-45-6789", 2423.07);
staffList[1] = new Employee ("Carla", "456 Off Line", "555-0101",
"987-65-4321", 1246.15);
staffList[2] = new Employee ("Woody", "789 Off Rocker", "555-0000",
"010-20-3040", 1169.23);
staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
"555-0690", "958-47-3625", 10.55);
staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
"555-8374");
staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
"555-7282");
/* ((Executive)staffList[0]).awardBonus (500.00);
((Hourly)staffList[3]).addHours (40);*/
}
public void payday ()
{
double amount;
for (int count=0; count < staffList.length; count++)
{
System.out.println (staffList[count]);
amount = staffList[count].pay();
if (amount == 0.0)
System.out.println ("Thanks!");
else
System.out.println ("Paid: " + amount);
System.out.println ("-----------------------------------");
}
}
public StaffMember[] getStaffList() {
return staffList;
}
public void setStaffList(StaffMember[] staffList) {
this.staffList = staffList;
}
}
package com.cisco.staff;
abstract public class StaffMember
{
protected String name;
protected String address;
protected String phone;
//-----------------------------------------------------------------
// Constructor: Sets up this staff member using the specified
// information.
//-----------------------------------------------------------------
public StaffMember (String eName, String eAddress, String ePhone)
{
name = eName;
address = eAddress;
phone = ePhone;
}
//-----------------------------------------------------------------
// Returns a string including the basic employee information.
//-----------------------------------------------------------------
public String toString()
{
String result = "Name: " + name + "\n";
result += "Address: " + address + "\n";
result += "Phone: " + phone;
return result;
}
//-----------------------------------------------------------------
// Derived classes must define the pay method for each type of
// employee.
//-----------------------------------------------------------------
public abstract double pay();
}
package com.cisco.staff;
import java.util.List;
public class EmployeeBinaryList
{
public static void main (String args[])
{
Staff staff = new Staff();
StaffMember[] staffList = staff.getStaffList();
for (int i = 0; i < staffList.length; i++)
System.out.println(staffList[i].toString());
}
}
package com.cisco.staff;
public class Executive extends StaffMember {
protected String somestrString;
protected double somelong;
public Executive(String eName, String eAddress, String ePhone, String someString , double pay) {
super(eName, eAddress, ePhone);
this.somestrString= someString;
this.somelong=pay;
// TODO Auto-generated constructor stub
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
package com.cisco.staff;
public class Volunteer extends StaffMember {
protected String somestrString;
protected double somelong;
public Volunteer(String name, String address, String phone) {
super(name, address, phone);
// TODO Auto-generated constructor stub
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
package com.cisco.staff;
public class Employee extends StaffMember {
protected String somestrString;
protected double somelong;
public Employee(String name, String address, String phone,
String somestrString, double somelong) {
super(name, address, phone);
this.somestrString=somestrString;
this.somelong=somelong;
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
package com.cisco.staff;
public class Hourly extends StaffMember {
protected String somestrString;
protected double hourly;
public Hourly(String eName, String eAddress, String ePhone, String somString, double hourly) {
super(eName, eAddress, ePhone);
this.somestrString=somString;
this.hourly=hourly;
// TODO Auto-generated constructor stub
}
#Override
public double pay() {
// TODO Auto-generated method stub
return 0;
}
}
I'm very new to programming and currently trying to write a car showroom application. I've got a vehicle class, showroom class and I'm trying to use a showroom driver for the input.
I'm having problems adding vehicle objects to my arraylist. Could someone point me in the correct direction.
My code:
public class Vehicle {
private String manufacturer;
private String model;
private String custName;
private String vin;
private String dateMan;
private String dateSold;
private Boolean sold;
private char tax;
private double cost;
public Vehicle(String a, String b, String c, String d) {
manufacturer = a;
model = b;
vin = c;
dateMan = d;
}
public String toString() {
String s = "Manufacturer: " + manufacturer + " Model: "
+ model + " vin: " + vin + "Date Manufactured:" + dateMan
+ "Cost: " + cost;
return s;
}
public void buyVehicle(String a, String b) { //buy method for the vehicle
a = dateSold;
b = custName;
sold = true;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public String getCustName() {
return custName;
}
public String getVin() {
return vin;
}
public String getDateMan() {
return dateMan;
}
public String getDateSold() {
return dateSold;
}
public Boolean getSold() {
return sold;
}
public char getTax() {
return tax;
}
public double getCost() {
return cost;
}
}
.
import java.util.ArrayList;
public class Showroom {
private ArrayList<Showroom> theVehicles;
public Showroom() {
theVehicles = new ArrayList<Showroom>();
}
public boolean addVehicle(Showroom newVehicle) {
theVehicles.add(newVehicle);
return true;
}
}
.
import java.util.*;
public class ShowroomDriver {
public static void main(String[] args) {
Vehicle v1 = new Vehicle("renault", "clio", "12", "290890");
Showroom.addVehicle(v1);
}
}
Basically, I'm confused to how I add vehicle objects to the arraylist within the showroom class. If anyone could point me in the right direction I would really appreciate it.
Thanks in advance.
You have to instantiate the class Showroom to use its properties and methods
The collection theVehicles is of Vehicle not Showroom.
package cars;
import java.util.ArrayList;
import java.util.List;
public class Showroom {
private final List<Vehicle> theVehicles = new ArrayList<>();
public boolean addVehicle( Vehicle newVehicle ) {
theVehicles.add( newVehicle );
return true;
}
public static void main( String[] args ) {
final Showroom showroom = new Showroom();
final Vehicle v1 = new Vehicle( "renault", "clio", "12", "290890" );
showroom.addVehicle( v1 );
}
}
in Vehicle class, a mistake around '=' operator, I suppose you want to memorize the sold value and the customer name:
public void buyVehicle( String a, String b ) { // buy method for the vehicle
dateSold = a;
custName = b;
sold = true;
}
I Think this
private ArrayList <Showroom> theVehicles;
Shoulde be this
private ArrayList <Vehicle> theVehicles;
theVehicles = new ArrayList <Vehicle> ();
And this
public boolean addVehicle( Showroom newVehicle )
Should be
public boolean addVehicle( Vehicle newVehicle )
Don't you want an ArrayList of Vehicles and not ShowRooms?
Your problem is that you declared an ArrayList of ShowRoom objects, but what you want is an ArrayList of Vehicle objects.
private ArrayList<Vehicle> theVehicles;
public boolean addVehicle(Vehicle v) {
theVehicles.add(v);
return true;
}