Based on a older question of mine Link I'm working on learning more about Casting and Instanceof. That is based upon a scenario described in a HeadFirst book
So basically I've now got a new class(Hybrid) that inherits from my Vehicle class what i'm trying to do is cast a Hybrid Object to display the extra information that comes with being a hybrid. It complies but doesn't really give me any idea what is causing the error except it just ends on the line i've marked.
public class ShowroomDriver {
public static void main(String[] args) {
Showroom cars = new Showroom("Cars");
Hybrid hybrid1 = new Hybrid("Toyota Prius", "Focus", "John Smith", "TOTAP453453987346283",
getCalendar(2,3,1998), getCalendar(24,2,2012),
"Right Hand",//Hybrid Only Info Edit: Forgot to commentout
true,
'C',
650, 82.0); //Cost & (Hybrid MPG)
cars.addVechicle(hybrid1);
cars.getVechicles();
Hybrid Class
import java.util.Calendar;
public class Hybrid extends Vehicle{
private double consumption;
private String drive;
public Hybrid(String Manufacture, String Model, String CustomerName, String Vin,
Calendar DateManufactured, Calendar Datesold, String Drive,
boolean HasbeenSold,
char TaxBand,
double Cost, double Consumption){
super(Manufacture, Model, CustomerName, Vin, DateManufactured, Datesold,
HasbeenSold,
TaxBand,
Cost);
this.consumption = Consumption;
this.drive = Drive;
}
public Double getConsumption() { return this.consumption; }
public String getDrive() { return this.drive; }
}
New Vehicle Method
public void displayDetails(){
for(int i = 0; i <cars.theVehicles.size(); i++){
if(this.cars.theVehicles.get(i) instanceof Hybrid){//Error here
Hybrid thehybrids = (Hybrid)this.cars.theVehicles.get(i);
System.out.println("Consumption: " + thehybrids.getConsumption()+ "\n" +
"Drive: " + thehybrids.getDrive());
}
}
}
Do you need to cast ? You've already overridden the displayDetails() method to display hybrid-specific info. So you should just be able to call this and the runtime will determine the correct method to call.
Related
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());
I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..
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.
Currently I am teaching myself Java but I came across a simple problem but have no one to ask from. From one of the exercises, I wrote a class and write a driver class that instantiates and updates several objects. I am confused by "instantiates and updates several objects." Here is what I mean: So here is my class:
public class PP43Car {
private String make = "";
private String model = "";
private int year;
public PP43Car(String ma, String m, int y)
{
make = ma;
model = m;
year = y;
}
public void setMake(String ma)
{
make = ma;
}
public String getMake()
{
return make;
}
public void setModel(String m)
{
model = m;
}
public String getModel()
{
return model;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public String toString()
{
String result = "Make of the vehicle: " + make +
" Model of the vehicle " + model +
" Year of the vehicle: " + year;
return result;
}
}
Which instantiates make, model and year. Then once I was writing the driver class, the way I began was:
import java.util.Scanner;
public class PP43CarTest {
public static void main(String[] args) {
PP43Car car1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the model of the vehicle:");
car1.getModel();
}
}
But this class produces error and here is where I am stuck. Do I keep on going with this or is this what is meant by "instantiating and updating several objects?"
import java.util.Scanner;
public class PP43CarTest {
static PP43Car car1;
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
car1 = new PP43Car("Millenia", "Mazda", 2011);
}
}
If the above code is correct, then can anyone show me how I can use the Scanner class to actually get the user input and update it that way because I would like to learn that as well?
Well, in your last fragment of code you are indeed instantiating an object, since you are doing:
car1 = new PP43Car("Millenia", "Mazda", 2011);
When you create a new object, you are creating a new instance of the class, so yes, you are instantiaing an object.
But you aren't updating it anywhere, because I think here updating means modifying the object, but you only create the object, not modify it...
Something like this would be an update:
car1.setYear(2013);
Since you are setting a different value for an attribute of the object, you are updating it...
EDIT: Try this code, it can't throw any exception, it's Java basics! I hope it clarifies your doubts...
public class PP43CarTest {
public static void main(String[] args) {
//Declaring objects
PP43Car car1;
PP43Car car2;
PP43Car car3;
//Instantiating objects
car1 = new PP43Car("Millenia", "Mazda", 2011);
car2 = new PP43Car("Aaaa", "Bbb", 2012);
car3 = new PP43Car("Ccc", "Ddd", 2012);
//Updating objects
car1.setMake("Xxx");
car1.setMake("Yyy");
car1.setYear(2013);
//Printing objects
System.out.println("CAR 1: " + car1.toString());
System.out.println("CAR 2: " + car2.toString());
System.out.println("CAR 3: " + car3.toString());
}
}
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.