This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm supposed to make a program that has MotorVehicle abstract class. Car, Truck, Van are kinds of MotorVehicle. The setTerms() and displayInfo() are the only abstract. Car has String transType and void Car(), Van has int numPassenger and void Van(), as Truck has double payLoad and void Truck().
The output should be like this:
Brand is Mazda
Vehicle type is Sedan
Color is Red
Transmission type is Automatic
Price is 840000.0
Terms is 5 years to pay
Brand is Isuzu
Vehicle type is Truck
Color is White
Payload capacity is 3.5
Price is 910000.0
Terms is 3 years to pay
Brand is Mitsubishi
Vehicle type is Family Van
Color is Blue
Number of passenger is 8
Price is 1050000.0
Terms is 7 years to pay
But my program doesn't still produce this output
Here's my current codes:
public abstract class MotorVehicle
{
private String vehicleType;
private String brand;
private String color;
private String terms;
public MotorVehicle(String vcl, String brn, String clr, String trm)
{
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public String getVehicleType()
{
return vehicleType;
}
public String getBrand()
{
return brand;
}
public String getColor()
{
return color;
}
public abstract void setTerms();
public abstract void displayInfo();
}
//=========================================
public class Car extends MotorVehicle
{
String transType="";
String vehicleType;
String brand;
String color;
String terms;
int price = 0;
public Car(String vcl, String brn, String clr, String trm)
{
super(vcl, brn, clr, trm);
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public void Car()
{
brand = "Mazda";
vehicleType = "Sedan";
color = "Red";
transType = "Automatic";
price = (int) (700000 + (700000*0.2));
Double.toString(price);
terms = "5";
}
public void setTerms()
{
return;
}
public void displayInfo()
{
System.out.println("Brand is " + brand);
System.out.println("Vehicle type is " + vehicleType);
System.out.println("Color is " + color);
System.out.println("Transmission type is " + transType);
System.out.println("Price is " + price);
System.out.println("Terms is " + terms + " years to pay");
}
}
//=================================
public class Truck extends MotorVehicle
{
double payLoad=0.0;
String vehicleType;
String brand;
String color;
String terms;
int price = 0;
public Car(String vcl, String brn, String clr, String trm)
{
super(vcl, brn, clr, trm);
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public void Truck()
{
brand = "Isuzu";
vehicleType = "Truck";
color = "White";
payLoad = 3.5;
Double.toString(payLoad);
price = (int) (700000 + (700000*0.3));
Double.toString(price);
terms = "3";
}
public void setTerms()
{
return;
}
public void displayInfo()
{
System.out.println("Brand is " + brand);
System.out.println("Vehicle type is " + vehicleType);
System.out.println("Color is " + color);
System.out.println("Payload capacity is " + payLoad);
System.out.println("Price is " + price);
System.out.println("Terms is " + terms + " years to pay");
}
}
//==========================
public class Van extends MotorVehicle
{
int numPassenger=0;
String vehicleType;
String brand;
String color;
String terms;
int price=0;
public Van(String vcl, String brn, String clr, String trm)
{
super(vcl, brn, clr, trm);
vehicleType = vcl;
brand = brn;
color = clr;
terms = trm;
}
public void Van()
{
brand = "Mitsubishi";
vehicleType = "Family Van";
color = "Blue";
numPassenger = 8;
String.valueOf(numPassenger);
price = (int) (700000 + (700000*0.5));
Double.toString(price);
terms = "7";
}
public void setTerms()
{
return;
}
public void displayInfo()
{
System.out.println("Brand is " + brand);
System.out.println("Vehicle type is " + vehicleType);
System.out.println("Color is " + color);
System.out.println("Number of passenger is " + numPassenger);
System.out.println("Price is " + price);
System.out.println("Terms is " + terms + " years to pay");
}
}
//===================
And this is the main program:
public class MainVehicle
{
public static void main(String[] args)
{
BBVehicle[] vhl= new BBVehicle[3];
int ctr=0;
while(ctr<3)
{
if (ctr==0)
vhl[ctr]=new Car();
else if(ctr==1)
vhl[ctr]= new Truck();
else
vhl[ctr]= new Van();
vhl[ctr].displayInfo();
ctr++;
}
}
}
I'm not sure with what's wrong with my program. help me please thanks
i)
public void Car()
public void Truck()
public void Van()
You are defining return type of Class Contructor
it should be
public Car()
public Truck()
public Van()
A constructor resembles an instance method, but it differs from a method in that it has no explicit return type, it is not implicitly inherited and it usually has different rules for scope modifiers.
ii) Define a no-argument constructor in the abstract class (From the comment)
iii)
BBVehicle[] vhl= new BBVehicle[3];
int ctr=0;
while(ctr<3)
{
if (ctr==0)
vhl[ctr]=new Car();
You are casting Car class to BBVehicle class. Although, both class are different. There is no relation between these two class..
The first piece of advice I would give is that you shouldn't hide your member variables from your superlcass.
In each of your child classes, you declare variables with the same name as the private variables that you define in your super class. Instead, you should simply remove the duplicates from the child classes and either:
change the visibility of the variables in the superclass to something that makes them available to child classes (ie protected)
utilize getters to access them in your displayInfo() method. To do this you would need to set a get[VariableName]() per field in your superclass.
Related
Writing a main class to output from 2 other classes. There are 6 variables being passed but only the last 3 are printing correctly. The first 3 all return null. Here is the output:
DOG DATA
null is a null, a null dog.
The top trick is : Spinner.
The Corgi is 12 years old and weighs 20 pounds.
public class Dog {
// instance variables
public static String type;
public static String breed;
public static String name;
public static String topTrick;
// constructor
public Dog(String type, String breed, String name) {
type = "No type";
breed = "No breed";
name = "No name";
}
// methods
public static String setTopTrick(String trick) {
topTrick = trick;
return trick;
}
// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}
}
ublic class Corgi extends Dog {
// additional instance variables
public static int weight;
public static int age;
// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}
// mutator methods
public static int setWeight(int pounds) {
weight = pounds;
return pounds;
}
public static int setAge(int years) {
age = years;
return years;
}
// override toString() method to include additional dog information
#Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}
}
public class Driver {
public static void main(String[] args) {
Corgi sleeper = new Corgi("Geriatric", "Pembroke Welsh", "Ein", 20, 12);
sleeper.setTopTrick("Spinner");
System.out.println(sleeper);
}
}
Literally everything in your program except main that is static should not be static. Static variables are not instance variables.
Also, your Dog constructor is incorrect, and should be
this.type = type;
this.breed = breed;
this.name = name;
I am trying to get user input for the number of seats a car has in the super class but make a method that prints the number of seats in the subclass called "Car". However, when I state the variable that stores the user input I get an error stating the variable is not visible and that is because it is in another class.
import java.util.Scanner;
class Vehicle {
Scanner s = new Scanner(System.in);
private String color;
private int noOfCylinders;
private int noOfSeats;
public Vehicle() {
color = "Black";
noOfCylinders = 0;
noOfSeats = 1;
}
public Vehicle(String color, int noOfCylinders, int noOfSeats) {
this.color = color;
this.noOfCylinders = noOfCylinders;
this.noOfSeats = noOfSeats;
}
public void getColor() {
System.out.print("Enter color of vehicle: ");
color = s.nextLine();
}
public String setColor() {
return color;
}
public void getNoOfCylinders() {
System.out.print("Enter number of cylinders: ");
noOfCylinders = s.nextInt();
}
public int setNoOfCylinders() {
return noOfCylinders;
}
public void getNoOfSeats() {
System.out.print("Enter numer of seats: ");
int noOfSeats = s.nextInt();
}
public String toString() {
String information;
information = "is " + color + " and it has " + noOfCylinders + " cylinders.";
return information;
}
}
public class CreateVehicle {
public static void main(String[] args) {
Car CarObject = new Car();
Truck TruckObject = new Truck();
CarObject.getColor();
CarObject.setColor();
CarObject.getNoOfCylinders();
CarObject.setNoOfCylinders();
CarObject.toString();
CarObject.getNumOfSeats();
TruckObject.getColor();
TruckObject.setColor();
TruckObject.getNoOfCylinders();
TruckObject.setNoOfCylinders();
TruckObject.toString();
System.out.print(("\nThe car ")+CarObject.toString());
System.out.print(("\nThe truck ")+TruckObject.toString());
}
}
class Car extends Vehicle{
public void getNumOfSeats(){
System.out.print("\nThe car has " + noOfSeats + " seats.");
}
}
class Truck extends Vehicle {
public void printTowingCapacity() {
System.out.print("\nThe car has " + towingCapacity + ".");
}
}
You can use the public function of the parent class, getNoOfSeats(), if you want to keep the variables private.
class Car extends Vehicle{
public void getNumOfSeats(){
System.out.print("\nThe car has " + super.getNoOfSeats() + " seats.");
}
}
Or just change the variable noOfSeats to protected or package-protected,
noOfSeats is a private member of the class which cannot be accessed by any other class. If you want to make it accessible from inherited class, make it access specifier to protected.
Based on OOP concept you can't access private variabale outside the class not even in child class.
Here you have declare
private int noOfSeats;
And you try to access it outside the class in child which is out of private variable scope.
To access it in child class make noOfSeats variable
public int noOfSeats;
or
protected int noOfSeats;
in Vehicle class.
If you want to put noOfSeats variable as private the create on public function on vehicitle class (parent class) and call it from Car class (child class).
And you are try to access
System.out.print("\nThe car has " + towingCapacity + ".")
towingCapacity variable in Truck class and you have't declare it in either Vehicle class or Truck class.
So first declare it then use it.
For more details about java access modifier read this article
https://www.softwaretestingmaterial.com/access-modifiers-in-java/
What an amazing platform! I hope im not asking a too stupid question but i have searched for an answer without success.
Q:
Is it possible to compare object values created by a constructor? Like if i want to make the animals fight and compare the "str" values against eachother.
My goal is to create the "fight" method in the Animal class, not in main. In that way, i can just call it like "dog.fight();
See my code for an example (sorry for my english)
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public void set (int strenght, int agility, String _name){
str = strenght;
agi = agility;
name = _name;
}
public String get (){
System.out.println("Created a new animal named " + name +"! ");
System.out.println(name + "'s agility is " + agi);
System.out.println(name + "'s strenght is " + str);
return name + str + agi;
}
}
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal ();
dog.set(8, 4, "Rambo");
dog.get();
System.out.println("");
Animal cat = new Animal ();
cat.set(2, 9, "Felix");
cat.get();
}
}
You need to create a method 'fight' in the Animal class the takes as parameter an Animal object and use it to return to you the result of the winner.
Here is the code :
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public void set (int strenght, int agility, String _name){
str = strenght;
agi = agility;
name = _name;
}
public String get (){
System.out.println("Created a new animal named " + name +"! ");
System.out.println(name + "'s agility is " + agi);
System.out.println(name + "'s strenght is " + str);
return name + str + agi;
}
public String fight(Animal rival){
//Provide Comparison Logic Here
if(this.str>rival.str)return this.name;
if(this.str < rival.str)return rival.name;
return "No One ";
}
}
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal ();
dog.set(8, 4, "Rambo");
dog.get();
System.out.println("");
Animal cat = new Animal ();
cat.set(2, 9, "Felix");
cat.get();
System.out.println(dog.fight(cat)+" is the winner! ");
}
}
A Small side notes here:
It would be much better to use constructors instead of set Method here, as normally setter and getter are created to set or get a single variable.
Also it's better to change the name of your get Method and override toString method.
Here's the modified code:
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public Animal (int str, int agi, String name){
this.str = str;
this.agi = agi;
this.name = name;
}
#Override
public String toString(){
String description = "Created a new animal named " + name +"!\n";
description+=name + "'s agility is " + agi+"\n";
description+=name + "'s strenght is " + str;
return description;
}
public String fight(Animal rival){
//Provide Comparison Logic Here
if(this.str>rival.str)return this.name;
if(this.str < rival.str)return rival.name;
return "No One ";
}
}
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal (8, 4, "Rambo");
System.out.println(dog);
System.out.println();
Animal cat = new Animal (2, 9, "Felix");
System.out.println(cat);
System.out.println(dog.fight(cat)+" is the winner! ");
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Directions: http://imgur.com/kw6A0JX
I don't think I am printing out the objects correctly. My teacher helped me with the first part so I believe I am assigning them correctly. When printing them out, do I use "this" command? What is the right syntax for this type of situation?
Thank you.
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(name.Dog1, getHello.Dog1, isCarnivorous.Dog1, isMammal.Dog1);
System.out.println(name.Sheep1, getHello.Sheep1, isCarnivorous.Sheep1, isMammal.Sheep1);
System.out.println(name.Duck1, getHello.Duck1, isCarnivorous.Duck1, isMammal.Duck1);
System.out.println(name.Cat11, getHello.Cat1, isCarnivorous.Cat1, isMammal.Cat1);
}
Updated:
public abstract class Animal1 { //creating Animal1 which is the base and parent class, it is abstract so abstract classes can be created below
private String animalName; //defining animalName as private
public int numberOfLegs; //# of legs as public
public Animal1(final String name){ //first constructor with only assigning name
animalName = name;
}
public Animal1(final String name, final int legs){ //second constructor assigning both name and number of legs
animalName = name;
numberOfLegs = legs;
}
public String getName(){ //first getMethod for animalName
return animalName;
}
public int getLegs(){ //second getMethod for returning numberOfLegs
return numberOfLegs;
}
public boolean isMammal(){ //returning true value with boolean
return true;
}
public boolean isCarnivorous(){ //returning true value with boolean
return true;
}
public abstract String getHello(); //creating an abstract method, possible because base class is also abstract
}
public class Cat1 extends Animal1{ //child class of Animal1
public Cat1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Meow"
return "Meow";
}
}
public class Dog1 extends Animal1{ //another child of Dog1
public Dog1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Woof"
return "Woof";
}
}
public class Duck1 extends Animal1{ //third child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isMammal(){ //Overriding isMammal() function to return false, as a duck is not a mammal
return false;
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a duck is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Quack"
return "Quack";
}
}
public class Sheep1 extends Animal1{ //fourth child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a sheep is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Baa"
return "Baa";
}
}
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
System.out.println(Wooly.getName() + ", " + Wooly.getHello() + ", " + Wooly.isCarnivorous() + ", " + Wooly.isMammal());
System.out.println(Daffy.getName() + ", " + Daffy.getHello() + ", " + Daffy.isCarnivorous() + ", " + Daffy.isMammal());
System.out.println(Ketty.getName() + ", " + Ketty.getHello() + ", " + Ketty.isCarnivorous() + ", " + Ketty.isMammal());
}
Your syntax is wrong. You need to refer to the variable by name, not by class. And the method comes after the object. And System.out.println() doesn't accept multiple arguments. Try this:
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
Similarly for the other lines.
You've got your syntax reversed. If these are all methods that you're calling, then they're done like Dog1.name(). If they're just public variables, you can call them like Dog1.name.
Also, a word of advice - most object instants in java follow the syntax of first word lowercase, following words uppercase (like your methods). Not crucial, but helpful to know.
Edit: Yep, it's just what the first line of this answer reads. To get the boolean from your animal class, just call them with first the object's name, then .exampleMethod().
Also, for your print statements, the println method might print the statements funny if you leave it as it is. What you can do instead is just add some strings in between like so:
System.out.println("Name: " + Dog1.getName() + ", Hello: " + Dog1.getHello()...); // rest of line excluded for brevity
The keyword this refers to the current object.
public class Test
{
public static void main(String[] args)
{
Dog1 dog = new Dog1("Rover", 4);
System.out.println(dog.name() + " " + dog.hello() + " " + dog.carnivorus() + " " + dog.mammal() + ".");
}
}
class Dog1
{
private String name;
private int age;
private String hello;
private boolean carnivorus;
private boolean mammal;
public Dog1(String name, int age)
{
this.name = name;
this.age = age;
this.hello = "woof woof";
this.carnivorus = true;
this.mammal = true;
}
public String name()
{
return this.name;
}
public String hello()
{
return this.hello;
}
public boolean carnivorus()
{
return this.carnivorus;
}
public boolean mammal()
{
return this.mammal;
}
}
I am a complete noob (5th day programming) which explains why I have spent countless head-aching hours trying to solve this problem and still have not figured it out yet:
How do you create an instance of CarAndBikes, load it with information of 3 cars and print it out?
Here's my incomplete code to give you an idea of the problem:
public class Vehicle {
String manufacturer, model;
int numberOfWheels;
public Vehicle(String manufacturer, String model, int numberOfWheels) {
this.manufacturer = manufacturer;
this.model = model;
this.numberOfWheels = numberOfWheels;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public String toString() {
return "(" + numberOfWheels +") '" + manufacturer + ", " + model + "'";
}
}
public class CarAndBikes {
private Vehicle[] items;
private int nextFreeItem = 0;
CarAndBikes (int size) {
items = new Vehicle[size];
for(int i = 0; i < size; i++)
items[i] = new Vehicle(manufacturer, model, numberOfWheels);
}
void addVehicle(String man, String mdl, int wheels) {
items[nextFreeItem++].addVehicle(man, mdl, wheels);
}
public String toString() {
return "(" + items + ")";
}
}
public class TestProgram extends CarAndBikes{
TestProgram(int size) {
super(size);
}
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle("Seat", "Ibiza", 4);
Vehicle vehicle2 = new Vehicle("Reliant", "Robin", 3);
Vehicle vehicle3 = new Vehicle("Honda", "Fireblade", 2);
System.out.println(vehicle1);
System.out.println(vehicle2);
System.out.println(vehicle3);
}
}
In my opinion you'd be better off separating cars and bikes into separating cars and bikes into two seperate classes 'Car' and 'Bike' and then create a 3rd class to house a collection of those objects, that way you can use an List or ArrayList to store them and have a method to just print them out.
import java.util.ArrayList;
Public Class Garage
{
private ArrayList<Vehicle> vehicles;
Public Garage()
{
vehicles = new ArrayList<Vehicle>();
}
public void addVehicle(Vehicle v)
{
vehicles.add(v);
}
public void getVehicles()
{
for(Vehicle v : vehicles)
{
System.out.Println(v.getModel());
}
}
}
You'll notice that the ArrayList accepts objects of type vehicle, well both cars and bikes extend vehicle so they will be accepted.
I notice the toString() method in CarAndBikes is using toString() on an array reference (and arrays don't override toString()). You could use Arrays.toString(Object[]) like
public String toString() {
// return "(" + items + ")";
return Arrays.toString(items);
}
The Object.toString() that you're getting is documented as,
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())