Print toString from different classes - java

I've been trying to figure this out for a while now, I've searched through various questions but I don't think I'm geting any closer.
I have a superclass Vehicle that gives various details of a vehicle. I then have my Car class which inherits from Vehicle.
I am trying to print the toString from my Car class, which overides the Vehicle class.
Basically I want to print out the information about each car.
Here is my main
public static void main(String []args)
{
Car Ford = new Car(Red, 4, true);
//Ford = Ford.; Tried various things here to no avail, kept getting nullfalse in output
Car Honda = new Car(Blue, 4, false);
System.out.println(Ford.vehicleDetails);
System.out.println("Honda");
}
}
This is my Vehicle class
public class Vehicle
{
// Variables
private String vehicleColour;
private int numberOfWheels;
String vehicleDetails;
// Constructor
public Vehicle(String vehicleColour, int numberOfWheels)
{
}
// Getters
public String getVehicleColour()
{
return vehicleColour;
}
public int getNumberOfWheels()
{
return numberOfWheels;
}
// Setters
public void setVehicleColour(String vehicleColour)
{
this.vehicleColour = vehicleColour;
}
public void setNumberOfWheels(int numberOfWheels)
{
this.numberOfWheels = numberOfWheels;
}
// Constructor
public Vehicle ()
{
}
// toString method super
public String toString() {
String vehicleDetails = (getVehicleColour() + "" + getNumberOfWheels());
return vehicleDetails;
}
}
And this is my Car class
public class Car extends Vehicle
{
// Variables
private boolean convertible;
Car vehicleDetails;
// Getter
public boolean getConvertible()
{
return convertible;
}
// Setter
public void setConvertible(boolean convertible)
{
this.convertible = convertible;
}
// Constructor
public Car(String vehicleColour, int numberOfWheels, boolean convertible) {
}
// toString method override
#Override
public String toString() {
return super.toString() + convertible;
}
}
I want my output to be something like "The Ford is red, has 4 wheels and is a convertible", with bold text coming from Vehicle and Car classes respectively.
How do I get the bold text to show up in output? Right now I just get default values such as null, 0 and false.
I appreciate any input, I know I am probably doing something really stupid that is really obvious but I just can't see it.
Thanks.

I want my output to be something like "The Ford is red, has 4 wheels and is a convertible"
For your above requirement simple solution:
System.out.println("The Ford is "+ Ford.toString() );
If you intend to get the whole output from Ford.toString then while creating Ford object you need to pass the car name too! Like shown below and make necessary changes in constructor for it!
Car Ford = new Car("Ford","Red", 4, true);
However constructors in Car and Vehicle class are made but no value is assigned to the local variables from them! Thus .toString() was not getting anything to show!
Required changes are:
In Main Class
System.out.println("The Ford is "+ Ford.toString() );
In Car Class
//change in the constructor
public Car(String vehicleColour, int numberOfWheels, boolean convertible) {
setNumberOfWheels(numberOfWheels);
setVehicleColour(vehicleColour);
setConvertible(convertible);
}
I am trying to print the toString from my Car class, which overides the Vehicle class.
//change in toString()
#Override
public String toString() {
if(convertible){
return super.toString() +"and is a convertible" ;
}else{
return super.toString() +"and is not a convertible" ;
}
}
In Vehicle Class
//change the constructor
public Vehicle(String vehicleColour, int numberOfWheels)
{
setNumberOfWheels(this.numberOfWheels);
setVehicleColour(this.vehicleColour);
}
Basically I want to print out the information about each car.
//change the toString()
public String toString() {
String vehicleDetails = (getVehicleColour() + ", has " +getNumberOfWheels()+" wheels");
return vehicleDetails;
}

I want my output to be something like "The Ford is red, has 4 wheels
and is a convertible", with bold text coming from Vehicle and Car
classes respectively.
If you want to include those words, then you have to tell it to include those words in your toString().
For example, if you want it to print "has 4 wheels", then you can't just do getNumberOfWheels(). Otherwise you just get a 4. You have to do something like "has " + getNumberOfWheels() + " wheels". If you don't tell it to include all the words, it won't know to include them.

Related

Store different object type in one array and print each one with their methods

I am trying to create a parent class for cars and subclasses from it. Each one has separate methods and store them in an array then if the class are subclass try to call the method on it.
Parent class
public class car {
public String name ;
public double price ;
public car (String name , int price) {
this.name = name ;
this.price = price;
}
public String toString() {
return "car name : "+this.name
+" Price : " +this.price ;
}
}
Sub class
public class CarMotors extends car {
public float MotorsCapacity ;
public CarMotors( String name, int price , float MotorsCapacity) {
super(name, price);
this.MotorsCapacity = MotorsCapacity ;
}
public float getMotorsCapacity() {
return this.MotorsCapacity;
}
}
Main class
public class Test {
public static void main(String[] args) {
car [] cars = new car[2] ;
cars[0] = new car("M3" , 78000);
cars[1] = new CarMotors("M4" , 98000 , 3.0f);
for(int i=0 ;i<2;i++){
if(cars[i] instanceof CarMotors) {
System.out.println(cars[i].getMotorsCapacity()); // error here
}else {
System.out.println(cars[i].toString());
}
}
}
}
As you can see, I can't print the getMotorsCapacity(). I am new to Java. I think there is a cast that need to happen, but I don't now how.
Being short... a class only can see what its yours behaviors.
In your example CarMotors is a Car, that's fine.
But the behavior getMotorsCapacity() is created in CarMotors and it wasn't in Car.
That error occurs because, it's OK in a variable Car you are able to put an instance of CarMotors because CarMotors is a Car. So, any method that is in Car is also in CarMotors, yes, you can call. Look at cars[i].toString() there's no problem here.
You need explicitly say to compiler:
"- oh, right, originally this variable is a Car, but I know that is a CarMotors inside that. I will make a cast here, OK compiler? Thanks."
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
Or, to be more clear:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());

Java - incorrect creation of subclasses and super classes

First, I think the title of this post could be better, so if you want to edit it feel free to do so (or let me know how you think I should edit it).
I am going over practice problems for Java interviews. I am not interviewing right now, but I think this is the best way for me to find all my weak spots with Java. And before you say it, yes, I am finding I am VERY weak in many areas of Java and that I will need to do lots or review before interviewing.
I have some questions about the following code:
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle() { }
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
make = "Ford";
numWheels = 4;
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
make = "Kawasaki";
numWheels = 2;
this.model = model;
this.year = year;
}
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}
First, I notice that there are no references to super() in the code. I thought that when you are dealing with super classes and subclasses, it was required that the subclass constructor include a reference to the super class constructor in the form of super(); (and including parameters if the super class constructor has them). Yet this code seems to work without them. Am I wrong about this requirement? Am I missing something else in this picture?
Second, the Kawasaki class doesn't include the decoration #Override for the countWheels() method. Since this method has the same name (albeit different parameters) as the super class' countWheels() method, wouldn't it be required to have an #Override decoration? Or is that only if the parameters are the same type and same order?
Thanks!
If you do not explicitly call super() in your derived class, the Java compiler will automatically generate a call to super() for you. But this, of course, only works if the base class constructor takes no arguments. This can be demonstrated by adding a System.out.println("Constructor called."); statement to your otherwise empty Vehicle constructor.
The #Override decorator, as you have found out but have not convinced yourself of, is optional. But it is considered a "best practice" to use this when overriding a method for catching errors if you change the method signature.
The one, hopefully constructive, comment I would make is that since a Vehicle must have attributes make and numWheels, I personally would require that these be specified in the Vehicle constructor. Now there is no possibility of having a derived class with these attributes undefined.
public class VehicleApp {
public static void main(String[] args) {
Ford myFord = new Ford();
System.out.println(myFord.countWheels());
Kawasaki myKawasaki = new Kawasaki(1985, "Eliminator");
System.out.println(myKawasaki.countWheels());
}
}
class Vehicle {
protected String make;
protected int numWheels;
public Vehicle(String make, int numWheels) {
this.make = make;
this.numWheels = numWheels;
}
public String countWheels() {
return "The number of wheels this " + make + " has is " + numWheels + ".";
}
}
class Ford extends Vehicle {
public Ford() {
super("Ford", 4);
}
}
class Kawasaki extends Vehicle {
private String model;
private int year;
public Kawasaki(int year, String model) {
super("Kawasaki", 2);
this.model = model;
this.year = year;
}
#Override
public String countWheels() {
return "The number of wheels this " + year + " " + make + " " + model + " has is " + numWheels + ".";
}
}

Wants static but can't support?

I am trying to create a random car generator that also displays info. I thought I had everything until the randomCar portion. It says that
'com.company.Main.this' cannot be referenced from a static context
under the return statements in the switch. Any thought on to where I may be going wrong?
package com.company;
public class Main {
class Car{
private String name;
private boolean engine;
private int cylinders;
private int wheels;
public Car(String name){
this.name = name;
}
public String getName(){
return name;
}
public int getCylinders() {
if(cylinders == 0){
System.out.println("Unknown amount of cylinders");
}
return cylinders;
}
public int getWheels() {
return wheels;
}
public boolean isEngine() {
return engine;
}
}
class Tacoma extends Car{
public Tacoma(String name) {
super("Tacoma");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 6;
}
public int getWheels(int wheels) {
return 4;
}
}
class Motorcycle extends Car{
public Motorcycle(String name) {
super("Harley Davidson");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 2;
}
public int getWheels(int wheels) {
return 2;
}
}
class Volvo extends Car{
public Volvo(String name) {
super("Volvo");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 4;
}
public int getWheels(int wheels) {
return 4;
}
}
public static void main(String[] args) {
for (int i = 1; i<6; i++){
Car car = randomCar();
System.out.println("Car # " + i + ":" + car.getName() + "\n" +
"Number of cylinders: " + car.getCylinders() + "\n" +
"Number of wheels: " + car.getWheels()+ "\n" +
"Engine is: " + car.isEngine());
}
}
private static Car randomCar() {
int randomNumber = (int) (Math.random()*5) +1;
System.out.println("Random number generated is: " + randomNumber);
switch (randomNumber){
case 1:
return new Tacoma(); // This is where I am getting an error
case 2:
return new Motorcycle(); // This is where I am getting an error
case 3:
return new Volvo(); // This is where I am getting an error
}
return null;
}
}
I would start by reading here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html -> actually all the chapters there would be useful for you to read: https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
Strictly speaking, to solve your "cannot be referenced from a static context" you can just make your classes static (Car, Tacoma, Motorcycle, Volvo) static class Car{
From my point of view you don't need nested classes, just create the classes in the same package as your Main class and you should be good to go (feel free to create more packages to better structure your classes)
Also I'm assuming your code is a work in progress because there are multiple issues with it:
methods like this don't make sense public boolean isEngine(boolean engine) {return true;} You receive a parameter that you ignore and you return a constant value: true; What I assume you want to do here is to have different types of cars each with its own predefined characteristics, but for that you should set the values for the attributes in the parent, Car. For this you either define protected setters, make the fields protected, or, best, create constructor which takes all the values
public Car(String name, boolean engine, int cylinders, int wheels) {
this.name = name;
this.engine = engine;
this.cylinders = cylinders;
this.wheels = wheels;
}
and you can have in Tacoma
public Tacoma(String name) {
super(name, true, 6, 4);
}
running your code I got the randomNumber 5 so that returned null and got a NPE, I assume work in progress
in your switch you are calling the default constructor new Tacoma() however that isn't available anymore since you defined a constructor with a parameter, use the available constructor or create the no-arg constructor.
There are other concerns regarding OOP principles so I recommend reading them again, just google "java OOP principles" and then "SOLID"... there are a lot of great resources out there, you just need time and patience and you'll get there!
When you put the Car class definition inside the class definition of Main, you made Car an inner class, so that a Car requires an outer class Main instance. In the static method there is no Main instance, and you can’t create the Car without it.
There is an immediate fix: add keyword static to the Car class:
static class Car {
which means there is no link to the enclosing object.
But there is no benefit here to making this a nested class, it would be better not to put one class definition inside another when you’re starting out.
The inner classes you've defined are instance members, meaning they belong to a specific instance of Main, and thus cannot be referenced from a static context that doesn't have a Main instance. The easiest way to resolve this would be to declare all the inner classes static.
First of all, to solve your error: 'com.company.Main.this' cannot be referenced from a static context, make all the methods static:
static class Car{//code here}
static class Volvo extends Car{//code here}
static class Tacoma extends Car{//code here}
static class Motorcycle extends Car{//code here}
Whenever you see that error, it means one static method is calling a non-static method. Therefore, just make both non-static or both static. The only exception is public static void main(String[] args); which must be static.
After solving the original errors, there is more to debug:
'Volvo(java.lang.String)' in 'com.company.Main.Volvo' cannot be applied to '()'
'Motorcycle(java.lang.String)' in 'com.company.Main.Motorcycle' cannot be applied to '()'
'Tacoma(java.lang.String)' in 'com.company.Main.Tacoma' cannot be applied to '()'
All this means is that your methods Tacoma(), Volvo(), and Motorcycle() require the parameter String name. So all you have to do is give them a name: here, it's
`new Tacoma("cool")`
new Volvo("car")
new Motorcycle("harley davidson")`
Finally, after solving the static and parameter problems, you are getting a NullPointerException, because randomCar() returns null. Your method says Car randomCar(), indicating it will return a Car, but then the return statement was return null;. Therefore, just return a Car - rtn here for our purposes:
private static Car randomCar() {
int randomNumber = (int) (Math.random()*5) +1;
System.out.println("Random number generated is: " + randomNumber);
Car rtn = null;
switch (randomNumber){
case 1:
rtn = new Tacoma("cool"); // This is where I am getting an error
case 2:
rtn = new Motorcycle("harley davidson"); // This is where I am getting an error
case 3:
rtn = new Volvo("car"); // This is where I am getting an error
}
return rtn;
}
This isn't all the debugging your code needs, but it's a start: here's what the system did so far:
Random number generated is: 3
Unknown amount of cylinders
Car # 1:Volvo
Number of cylinders: 0
Number of wheels: 0
Engine is: false
Random number generated is: 5
Hooray!
Did this help?

Why can't I seem to find the error in my program when compiling. Help needed

The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.

Overriding a Method in Java

Ok, so I'm just learning java, and using this: http://www.myflex.org/books/JavaKid8x11.pdf tutorial. I'm currently on page 37, and I can't seem to over ride the fish. I'm pretty sure I copied the code exactly, but obviously I'm doing something wrong, so here is my code.
Here is the class Pet:
public class Pet {
int age;
float weight;
float height;
String color;
public void sleep() {
System.out.println(
"Good night, see you tommorow");
}
public void eat() {
System.out.println(
"I'm so hungry...let me have a snack like nachos!");
}
public String say(String aWord) {
String petResponse = "OK!! OK!! " +aWord;
return petResponse;
}
}
That is the Super Class of the class of Fish:
public class Fish extends Pet {
public String say(String something) {
return "Don't you know that fish do not talk?";
}
int currentDepth=0;
public void sleep() {
System.out.println("I need to rest");
}
public int dive(int howDeep) {
currentDepth=currentDepth + howDeep;
System.out.println("Diving for " + howDeep + " feet");
System.out.println("I'm at " + currentDepth + " feet below sea level");
return currentDepth;
}
}
The Fish class is used by FishMaster:
public class FishMaster {
public static void main(String[] args) {
Fish myLittleFish = new Fish();
myLittleFish.say("Hello!");
myLittleFish.dive(2);
myLittleFish.dive(3);
myLittleFish.sleep();
}
}
The problem is when I'm trying to over ride the say method in the Fish class. While over riding the sleep method worked fine, the say method doesn't do anything anymore. I run it, and it doesn't print "Don't you know fish can't talk?" as the book says it should. Am I doing something wrong, or is the say function just suppose to not print anything. Feedback is appreciated, thanks.
The method returns a String, it doesn't print it. Try:
System.out.println(myLittleFish.say("Hello!"));
To clarify:
// we assign the string returned from the method to a variable
String sentence = myLittleFish.say("Hello!");
// we print the variable to screen
System.out.println(sentence);
All your say() method does is return a String. The calling function (FishMaster.main()) doesn't do anything with this String. I expect you wanted to print it out with:
System.out.println(myLittleFish.say("Hello!"));
You forgot to print it to system out. The value is being returned just not printed.

Categories