toString() method is not inherting from its super class - java

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!";

Related

How to check between two subclasses which one has been called when creating an instance?

I'm trying to create a "bank account" with its operations. Some of them are:
bank addition : class Ajout
bank withdrawal : class Retrait
There are the bank balance variable named solde and amount named montant
The AjoutOuRetrait class is the mother class (means AdditionOrWithdrawal)
Now what I expect in my main class is the following:
c1.operation(new Ajout(750, new Date(01,01,2017)));
c1.operation(new Retrait(50, new Date(05,03,2017)));
System.out.println(c1.getSolde()); // result -> 700
public class AjoutOuRetrait {
public int montant;
public Date date;
public AjoutOuRetrait(int montant, Date d) {
this.montant = montant;
this.date = d;
}
public class CompteBancaire {
private String id;
private Banque banque;
private int solde;
public CompteBancaire(String id, Banque b) {
this.id = id;
this.banque = b;
}
public void operation(AjoutOuRetrait aor){
this.solde = aor.montant;
}
more the getters and setters that I omitted.
public class Retrait extends AjoutOuRetrait {
public Retrait(int montant, Date d) {
super(montant, d);
}
}
public class Ajout extends AjoutOuRetrait{
public Ajout(int montant, Date d) {
super(montant, d);
}
I was thinking on a way to differentiate (with conditional statement) which child class I call in argument of operation() method , whether it is Retrait (WithDrawal) -- or Ajout(Additional) ++
You might check the child type in operation like.
public void operation(AjoutOuRetrait aor){
if(aor instanceof Ajout) {
this.solde += aor.montant;
} else if (aor instanceof Retrait) {
this.solde -= aor.montant;
}
}
or split them
public void operation(Ajout a){
this.solde += a.montant;
}
public void operation(Retrait r){
this.solde -= r.montant;
}
Also you might get the value used as right operand of your operation like
public class AjoutOuRetrait {
public int getValue() {
return this.montant;
}
}
public class Retrait {
#Override
public int getValue() {
return -this.montant;
}
}
public void operation(AjoutOrRetrait aor) {
this.solde += aor.getValue();
}

How to stop printing half of my print method

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";
}
}

Writing a static method for the following code

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());

interface,abstract and classes

I am trying to complete the Appendix attached Appendix. I just want to know if I am coding it correctly according to the Appendix and that I am using the correct approach. I am not sure if I did the correct thing under interest(). Where I called the super classes is that correct?
public interface LoanInterest {
double interest();
String getName();
String toString();
} //end of LoanInterest
public abstract class Student implements LoanInterest {
private String name;
private String studentNumber;
private double feesOwed;
public Student(String nm, String num, double amt) {
name = nm;
studentNumber = num;
feesOwed = amt;
}
public double getFeesOwed() {
return feesOwed;
}
public String getStudentNumber() {
return studentNumber;
}
public String getName() {
return name;
}
public String toString() {
String msg;
msg = String.format("%s\t%s\t%.2f", name, getStudentNumber(), getFeesOwed());
return msg;
}
} //end of Student
public class UnderGrad extends Student {
public UnderGrad(String nm, String num, double amt) {
super(nm, num, amt);
}
public double interest() {
return super.getFeesOwed() + (super.getFeesOwed() * 0.14);
}
} //end of UnderGrad
public class PostGrad extends Student {
private String diploma;
public PostGrad(String nm, String num, double amt) {
super(nm, num, amt);
}
public String getDiploma() {
return diploma;
}
public double interest() {
return super.getFeesOwed() + (super.getFeesOwed() * 0.14);
}
} //end of PostGrad
You don't need to call super.methodName, since you do not override them in PostGrad or UnderGrad, but it is not "wrong" either.
So you can write:
public double interest() {
return getFeesOwed() + (getFeesOwed() * 0.14);
}
And if you would override them, you most likely want to use them too, so again no super.
The super keyword is normally used, if a method is overridden to add some additional functionality to it, without completely rewriting the code of the overridden method.

Overriding and printing classes

I'm just trying to Override and use the toString method to print some information about my classes.
Can someone please provide advice as to how I would do this?
I've never done this before, and I'm becoming stuck.
My Base Class:
public class Vehicle {
int seatNumber;
int numberMade;
int yearMade;
public Vehicle(int seatNumber, int numberMade, int yearMade) {
this.seatNumber = seatNumber;
this.numberMade = numberMade;
this.yearMade = yearMade;
}
public int getSeatNumber() {
return seatNumber;
}
public int getNumberMade() {
return numberMade;
}
public int getYearMade() {
return yearMade;
}
}
A derived class:
public class Car extends Vehicle {
public int topSpeed;
public Car(int seatNumber, int numberMade, int yearMade, int topSpeed) {
this.seatNumber = seatNumber; //takes the value you pass as parameter
this.numberMade = numberMade; // and stores it into the instance variable
this.yearMade= yearMade;
this.topSpeed = topSpeed;
}
}
Main Class:
public class Assignment2 {
public static void main(String[] args) {
Car myCar = new Car(5, 20000, 1998, 180);
Motorbike myMotorbike = new Motorbike(1, 5000, 2015, 300);
System.out.println(myCar);
System.out.println(myMotorbike);
}
}
You can do it like this:
public class Vehicle {
int seatNumber;
int numberMade;
int yearMade;
// Getters, setters, constructor, etc
#Override
public String toString() {
return String.format("[Vehicle] seats: %d, number made: %d, yearMade %d", seatNumber, numberMade, yearMade);
}
}
Same for the other Class
I'm just trying to Override and use the toString method to print some information about my classes
There are 2 ways you can override a method in the subclass.
Override by modification
Override it with new implementation
Can someone please provide advice as to how I would do this?
Overridding in Java is very simple. Just rewrite the method with similar method signature in the subclass according to the method in its super class.
Below shows an example of overriding by modification:
class Animal
{
#Override
public String toString(){
return "An animal";
}
}
class CatFamily extends Animal{
#Override
public String toString(){
return super.toString() + " from the cat family.";
}
}
class Lion extends CatFamily{
#Override
public String toString(){
return super.toString() + " - A Lion";
}
}
Create a super & subclass instance for testing:
public static void main(String[] args)
{
System.out.println(new Animal());
System.out.println(new CatFamily());
System.out.println(new Lion());
}
OUTPUT:
An animal
An animal from the cat family.
An animal from the cat family. - A Lion

Categories