Overriding a Method in Java - 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.

Related

Print toString from different classes

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.

How to get my program to print out?

Having trouble trying to get my program to work for my AP Computer Science class. Comments have been made inside the code to show my problem. Thanks guys/gals.
Java Class
import java.util.*;
public class Allosaur extends Dinosaur
{
private boolean hungry;
private String response, answer;
private String Allosaur;
// Prompt asks for 3 constructors: A Default constructor, a constructor with just a name, and a constructor with a name and hunger "response"
public Allosaur()
{
}
public Allosaur(String name)
{
Allosaur=name;
}
public Allosaur(String name, boolean hungry)
{
Allosaur=name;
this.hungry=hungry;
}
// Used this method to "find out" whether the dinosaur is hungry or not
public boolean getHunger()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Are you hungry? ");
response = keyboard.next();
if(response.equals("Yes"))
hungry = true;
else if(!response.equals("Yes"))
hungry= false;
return hungry;
}
// Asks us to print out "RRRRRRR" if the dinosaur is NOT hungry and "HUNGRRRRRRRY" if the dinosaur IS hungry
public String roar()
{
if(hungry == true)
answer = "HUNGRRRRRRRY";
else if(hungry == false)
answer = "RRRRRRR";
return answer;
}
//When I use the toString() method in my driver class, none of these pop up, why?
public String toString()
{
String Dino = super.toString();
Dino = "The Dinosaur's name is: " + Allosaur;
Dino += "Is the Dinosaur hungry? :" + getHunger() + "\n" + roar();
return Dino;
}
}
And here is my Driver Class:
public class DinosaurMain extends Allosaur
{
public static void main(String[] args)
{
Allosaur Dino = new Allosaur("Jacob");
Dino.toString();
}
}
I'm very confused as to why nothing will show up when I run the program.
Nothing shows up after the String input is requested because you're simply doing the call in DinosaurMain as Dino.toString(). This just makes the String representation for your object. It doesn't print that String representation out. If you were to change it to System.out.println(Dino.toString()); you would see the result.

Call data from a string array to another class

public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}

Error: 'void' type not allowed here [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?
public class TestCar {
public static final void main(String args[]) {
Car c = new Car ();
c.moveForward(4);
System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
}
}
class Car {
public int miles = 2000;
public void moveForward(int mf) {
if (miles != 2000) {
miles += mf;
}
}
public void mileage() {
System.out.print(miles);
}
}
The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.
Instead, have the mileage() method return a String, not print out a String.
public String mileage() {
return String.valueOf(miles);
}
Myself, I'd make this a getter method, and instead would do:
public int getMiles() {
return miles;
}
Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:
public int mileage() {
return miles;
}

Java-How do I call a class with a string?

I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.

Categories