Different values for each subclass - java

I would like to create a school(Houses) with 4 subclasses that take a basic values from the superclass(color, logo etc, each subclass with different values) and keep track, each sub class to itself of the number of students and points.
I also want to grant the ability to add points only for instance of Houses directly.
This is the code:
public class Houses {
int students = 75;
String color;
String logo;
String Founder;
String Trait;
String name;
int points = 0;
protected void Welcome() {
System.out.println("Welcome to " + name + "! \n This house was founded by " +
Founder + " and his core value is " + Trait + " , the house logo is " + logo
+ " and his color is " + color + "\n We have right now " + students + " students and "
+ points + " points. BEST OF LUCK!");
}
public void AddPoints(int x){
points += x;
System.out.println(x + " Points added!\nYour house now have " + points + " points");
}}
public class Gryffindor extends Houses {
Gryffindor() {
name = "Gryffindor";
students += 1;
color = "Red";
logo = "Lion";
Founder = "Godric Gryffindor";
Trait = "Brave";
Welcome();
}}
if im making the students and point as static its working fine but of course it add up all the sub classes together.
the best idea is to declare the values students and points inside each subclass as static?
Thanks for your time!

Looks like a misuse of sub-classes. Unless each sub-class is going to have it's own unique functionality, then each set of data should be associated to an instance of a House. You'd then most likely want to use the Constructor to set this data.
House Class
public class House {
int students;
String name;
String color;
//Other class variables
public House(int students, String name, String color) {
this.students = students;
this.name = name;
this.color = color;
}
//Various methods
}
Main Class
public class HouseTest {
public static void main(String[] args) {
House gryffindor = new House(75, "Gryffindor", "Red");
House ravenclaw = new House(68, "Ravenclaw", "Blue");
}
}
However, if you really want to set this data using a sub-class you can make use of the House constuctor via the super keyword which calls the parent constructor. Using the House from my code above it would be:
Gryffindor Class
public class Gryffindor extends House {
public Gryffindor() {
super(75, "Gryffindor", "Red");
//Set value for anything unique to Gryffindor here after super keyword
}
//Gryffindor specific methods
}

I will use a singleton School class to keep a single state count of students and points throughout the program. So create a class with those values you want to keep a single state track of and make them the class fields.
A singleton is a class that is instantiated once in memory and have the object shared by all classes within the application. This single state object in memory hold single state data points.
public class School{
private int students = 75;
private int points = 0;
private static final School instance = new School();
private School() {}
public static School getInstance() { return instance; }
public synchronized void addStudent() {
students++;
}
public synchronized void addPoints(int x) {
points += x;
}
public synchronized int getStudents() { return students; }
public synchronized int getPoints() { return points; }
}
So your House class will look like:
public class Houses {
School school = School.getInstance();
int students = school.getStudents();
String color;
String logo;
String Founder;
String Trait;
String name;
int points = school.getPoints();
protected void Welcome() {
System.out.println("Welcome to " + name + "! \n This house was founded by " +
Founder + " and his core value is " + Trait + " , the house logo is " + logo
+ " and his color is " + color + "\n We have right now " + students + " students and "
+ points + " points. BEST OF LUCK!");
}
public void AddPoints(int x){
school.addPoints(x);
System.out.println(x + " Points added!\nYour house now have " + points + " points");
}}
And your Gryffindor class
public class Gryffindor extends Houses {
Gryffindor() {
name = "Gryffindor";
school.addStudent();
color = "Red";
logo = "Lion";
Founder = "Godric Gryffindor";
Trait = "Brave";
Welcome();
}}

Related

Java toString in class

I am getting an error of cannot find symbol in my code posted below. I am trying to initalise a sedan using it's class and have the toString function right after but nothing is working for me. Please help
class cars {
String make;
String model;
String color;
int year;
double price;
public String sedancClass(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " " + year + " costs $" + price);
return main;
}
}
public class autoPark {
public static void main(String args[]) {
cars sedan1;
sedan1 = new sedanClass("Ford" , "Model-1" , "white" , 2015, 20000);
}
}
According to what you provided, I think this is what you are trying to do
class cars {
String make;
String model;
String color;
int year;
double price;
// parametised constructor
public cars (String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " " + year + " costs $" + price);
return main;
}
}
public class autoPark {
public static void main(String args[]) {
cars sedan1; // declaring cars object by name sedan1
sedan1 = new cars("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using cars constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
}
}
Why we use #Override annotation source
Using #Override annotation while overriding a method is considered as a best practice for coding in java because of the following two advantages:
If programmer makes any mistake such as wrong method name, wrong parameter types while overriding, you would get a compile time error. As by using this annotation you instruct compiler that you are overriding this method. If you don’t use the annotation then the sub class method would behave as a new method (not the overriding method) in sub class.
It improves the readability of the code. So if you change the signature of overridden method then all the sub classes that overrides the particular method would throw a compilation error, which would eventually help you to change the signature in the sub classes. If you have lots of classes in your application then this annotation would really help you to identify the classes that require changes when you change the signature of a method.

OOP Inheritance homework (Animal to lion super class inheritance) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to:
Extend the animal class with a Lion class and have different features(done).
Add a field called Liontype class and add a method classifying the lion type per its weight.(Needs to be derived from the superclass)
And print it out.
There are errors in my code and I've been trying to fix it.
Thank for any assistance in advance.
public class Animal {
private int numTeeth = 0;
private boolean spots = false;
private int weight = 0;
public Animal(int numTeeth, boolean spots, int weight){
this.setNumTeeth(numTeeth);
this.setSpots(spots);
this.setWeight(weight);
}
public int getNumTeeth(){
return numTeeth;
}
public void setNumTeeth(int numTeeth) {
this.numTeeth = numTeeth;
}
public boolean getSpots() {
return spots;
}
public void setSpots(boolean spots) {
this.spots = spots;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
//Extend animal class
public class Lion extends Animal{
public Lion (int numTeeth, boolean spots, int weight){
super(numTeeth, spots, weight);
//Add new attributes
int age = 0;
int cubs = 0;
}
public static void main(String args[]){
//Create lions and assign attributes
Lion lion1 = new Lion();
lion1.numTeeth = 12;
lion1.spots = 1;
lion1. weight = 86;
lion1.age = 7;
lion1.cubs = 3;
//Print attributes
System.out.println("Lion1 attributes:");
System.out.println("Number of teeth : " + numTeeth);
System.out.println("Number of spots : " + spots);
System.out.println("Weight of lion : " + weight + " kgs");
System.out.println("Age : " + age);
System.out.println("No of cubs : " + cubs);
System.out.println(" ");
Lion lion2 = new Lion();
lion2.numTeeth = 16;
lion2.spots = 0;
lion2. weight = 123;
lion2.age = 13;
lion2.cubs = 5;
System.out.println("Lion2 attributes:");
System.out.println("Number of teeth : " + numTeeth);
System.out.println("Number of spots : " + spots);
System.out.println("Weight of lion : " + weight + " kgs");
System.out.println("Age : " + age);
System.out.println("No of cubs : " + cubs);
System.out.println(" ");
}
public class Liontype{
//Trying to get weight from another class
public Integer getWeight()
{
if (weight > 120)
{
System.out.println("This lion is a cub");
}
else if (weight >= 120 && weight < 180)
{
System.out.println("This lion is a female");
}
else if (weight >= 180)
{
System.out.println("This lion is a male");
}
}
}
}
Expected outcome:
Lion attributes:
Number of teeth : 16
Spots : true
Weight of lion : 83kgs
Age : 13
No of cubs : 3
This lion is a female
In addition to errors pointed out by Dmitry, your main in the Lion class has the following:
public static void main(String args[]){
//Create lions and assign attributes
Lion lion1 = new Lion();
lion1.numTeeth = 12;
lion1.spots = 1;
lion1. weight = 86;
lion1.age = 7;
lion1.cubs = 3;
numTeeth spots weight and all the other fields are set private. Your Lion class can't access these fields directly. You are supposed to use your getters and setters you from the Animal
Also when printing attributes in Lion:
//Print attributes
System.out.println("Lion1 attributes:");
System.out.println("Number of teeth : " + numTeeth);
System.out.println("Number of spots : " + spots);
System.out.println("Weight of lion : " + weight + " kgs");
System.out.println("Age : " + age);
System.out.println("No of cubs : " + cubs);
System.out.println(" ");
your fields are attributes to an object. Trying to print the fields directly will give you an compiler error because those are properties of your Lion1 object. You need to use the dot operator like this:
System.out.println("Number of Teeth" + Lion1.getNumTeeth());
Yes, there are many problems in your code that will be obtained at the compilation stage. Perhaps you incorrectly specified your examples. So, please provide details of your problem.
I will point out some that are immediately evident:
You declared local variables
int age = 0;
int cubs = 0;
in the constructor that doesn't actually extend the class Lion with new attributes. Add these attributes as a fields as you did to the class Animal:
private int age = 0;
private int cubs = 0;
and then initialize them in the constructor of the class Lion (if necessary).
In the method public static void main(String args[]), you are trying to use
Lion class fields age, cubs that it does not have. See point 1.
The public Integer getWeight() of the class Liontype has 2 errors. Firstly, the variable weight is not defined, and secondly there is missing the return statement, although the method must return a Integer value.

Java - adding to an inherited JOptionPane

Good evening all!
I think there's something I don't understand here about either inheritance or JOptionPane, but basically I want to figure out how to actually use a new JOptionPane in the LuxuryCarRental subclass.
Currently it displays 2 dialog boxes if the choice is "l", one box from the parent class and a new one I added in the subclass. Ideally I would want only one dialog box. I think this is something that I can do without JOptionPane but I would like to try to make it work with JOptionPane if possible.
My code:
CarRental.java (parent class)
import javax.swing.JOptionPane;
public class CarRental
{
private String name;
private String zipCode;
private String size;
private double dailyFee;
private int rentalDays;
private double totalFee;
public CarRental(String name, String zipCode, String size, int rentalDays)
{
this.name = name;
this.zipCode = zipCode;
this.size = size;
if (size.equals("e"))
{
dailyFee = 29.99;
}
else if (size.equals("m"))
{
dailyFee = 38.99;
}
else if (size.equals("f"))
{
dailyFee = 43.50;
}
this.rentalDays = rentalDays;
totalFee = dailyFee * rentalDays;
}
public void display()
{
JOptionPane.showMessageDialog(null, "Car for " + name + " from zip code " + zipCode + "\n"
+ "Type = " + size + "\n"
+ "Daily Fee = " + dailyFee + "\n"
+ "Days = " + rentalDays + "\n"
+ "Your rental is $" + totalFee);
}
//includes getters and setters but I didn't include this in this post
LuxuryCarRental.java (subclass)
import javax.swing.JOptionPane;
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String name, String zipCode, String size, int rentalDays)
{
super(name, zipCode, size, rentalDays);
if (size.equals("l"))
{
this.setDailyFee(79.99);
String includeChauffeur;
includeChauffeur = JOptionPane.showInputDialog(null, "Include chauffeur? Y/N");
if (includeChauffeur.equals("Y") || includeChauffeur.equals("y"))
{
this.setDailyFee(279.99);
this.setTotalFee(this.getDailyFee()*this.getRentalDays());
JOptionPane.showMessageDialog(null, "Chauffeur # $200/day = $" + 200 * this.getRentalDays());
}
}
}
}
UserCarRental.java (driver class)
import javax.swing.JOptionPane;
public class UseCarRental
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog("Enter name");
String zip = JOptionPane.showInputDialog("Enter zip code");
String size = JOptionPane.showInputDialog("Enter type of car" + "\n" + "e - economy" + "\n" + "m - midsize" + "\n" + "f - full" + "\n" + "l - luxury");
int days = Integer.parseInt(JOptionPane.showInputDialog("Enter days to rent"));
CarRental userInfo = new LuxuryCarRental(name, zip, size, days);
userInfo.display();
}
}
Any help would be greatly appreciated!
I think that the lesson here is to not mix UI code with model code. Understand that your CarRental class and all of its subclasses are logical or model classes, and can be thought of here as classes that model a physical or logical reality. They should be used in this capacity, and should be written so information can be passed into them and extracted out of them, but they should not interact directly with the user. Instead that is the responsibility of the UI (user interface) classes, of which here it is quite simple and only your main method. So I suggest that you get your JOptionPane calls out of both CarRental and LuxeryCarRental, and instead display the JOptionPane in your main method after extracting state from your CarRental object.
Otherwise, if you absolutely must have the model classes display their information, then do it in a method that can be fully overridden. In fact you would have your child class override the display() method, and then print out its data there.

Error: method in class cannot be applied to given type

I'm getting this error message for my getYear, getMake, and getModel methods within my class car, because apparently they aren't being passed arguments. It appears to me that they are being passed arguments, but I'm still in a beginner in Java, so I'm not sure where I messed up.
public class NextCar {
public static final void main(String args[]) {
//Creates objects from Car class
Car c = new Car ();
Car c1 = new Car ();
Car c2 = new Car ();
Car c3 = new Car ();
//First object
//Prints mileage
c.start();
c.moveForward(6);
c.moveBackward(2);
c.moveForward(4);
System.out.println ("The car went " + c.mileage() + " miles.");
//Second object
//Prints year of car
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
//Third object
//Prints year and make of car
c2.getYear(2055);
c2.getMake("Google");
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
//Fourth object
//Prints year, make, and model of car
c3.getYear(2060);
c3.getMake("Google");
c3.getModel("Smart");
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
c3.getMake() + " and the model is " + c3.getModel());
}
}
//creates Car class
class Car {
public int year = 0;
public String make = "";
public String model = "";
public int miles = 0;
public boolean power = false;
public void start() {
power = true;
}
public void moveForward(int mf) {
if (power == true) {
miles += mf;
}
}
public void moveBackward(int mb) {
if (power == true) {
miles -= mb;
}
}
public int mileage() {
return miles;
}
public int getYear(int y) {
year = y;
return year;
}
public String getMake(String ma) {
make = ma;
return make;
}
public String getModel(String mo) {
model = mo;
return mo;
}
}
Your Car class getYear method takes an integer input:
public int getYear(int y)
but you call it few times without providing an input
System.out.println("The year of the car is " + c1.getYear());
System.out.println("The year of the car is " + c2.getYear() + " and the make is " + c2.getMake());
System.out.println("The year of the car is " + c3.getYear() + " and the make is " +
thats the reason for your errors.
You probably want two methods getYear(to get the year value) and setYear (to set the year value) but you have defined only one. Probably this is what you need:
public void setYear(int y) {
year = y;
}
public int getYear() {
return year;
}
Furthermore look here:
c1.getYear(2050);
System.out.println("The year of the car is " + c1.getYear());
the getYear return a value. so you could do
int year = c1.getYear(2050);
System.out.println("The year of the car is " + year);
Similar for the others. Or as Juned said, use appropiate getters/setters

Creating a car class in java

Okay, I need to write code that makes this file
public class HW1tester
{
public static void main(String[] args)
{
Car car1 = new Car();
Car car2 = new Car("Ford", 2013, 20000);
Car car3 = new Car("Audi", 2012, 25000);
Car car4 = new Car();
car2.setPrice(22000);
car2.setYear(2011);
car4.setBrand("Cadillac");
System.out.println("This car is " + car1.getBrand() + ", year " + car1.getYear() + ", price " + car1.getPrice());
System.out.println("This car is " + car2.getBrand() + ", year " + car2.getYear() + ", price " + car2.getPrice());
System.out.println("This car is " + car3.getBrand() + ", year " + car3.getYear() + ", price " + car3.getPrice());
System.out.println("This car is " + car4.getBrand() + ", year " + car4.getYear() + ", price " + car4.getPrice());
System.out.println("The total car number is: " + car1.getNumber());
System.out.println("The total car number is: " + car2.getNumber());
System.out.println("The total car number is: " + car3.getNumber());
System.out.println("The total car number is: " + car4.getNumber());
}
}
So far I have this, but I'm not sure what the hell I'm doing wrong.
public class Car
{
private int yearModel;
private String brand;
private int priceModel;
private int numberModel;
public Car(String b, int year, int price, int number)
{
yearModel = year;
brand = b;
priceModel = price;
numberModel = number;
}
public int getYear()
{
return yearModel;
}
public String getBrand()
{
return brand;
}
public int getPrice()
{
return priceModel;
}
public int getNumber()
{
return numberModel;
}
public void setYear(int year)
{
yearModel = year;
}
public void setBrand(String carBrand)
{
brand = carBrand;
}
public void setPrice(int price)
{
priceModel = price;
public void setNumber(int number)
{
numberModel = number;
}
}
Everytime I run the first code right now it just gives me errors on car1, car2, etc I just can't seem to see what I'm doing wrong at all, I hope somebody can help me out. By the way, I can't make ANY changes to HW1tester.
When creating a new object (car1, car2, etc.), you're not passing in enough variables. Your constructor requires 4 and you're giving, at most, 3 variables when trying to construct a new car object.
You have created parameterized Constructor i.e. public Car(String b, int year, int price, int number)
So when you are trying to create object for the same like, Car car1 = new Car(); then it won't be possible. Because in this you are trying to call default constructor. Which is not present in the class.
While creating object you need to pass 4 arguments.
Moreover, in Car car2 = new Car("Ford", 2013, 20000); You are passing 3 arguments which doesn't match with the constructor.
To create object of class Car, you need to do something like,
Car c = new Car('Volvo', 2014, 25000, 1234);
you need to write overloaded constructors with different parameter sets.
when you call new Car(), java is looking for a ctor with no params, new Car("audi", 2013, 25000) one with 3 params etc.
in your Car.java file:
public Car() {}
then you can set the instance variables with their getters and setters (until you do, their values will be null).
if you want, you can define more, but their signatures have to be different. eg:
public Car(String b, int year) { ... } and public Car(String b, int price) {...} wont work, because they have the same signature.
In class Car, you have a constructor that has 4 parameters. However in the main class, you create a Car with 0 or 3 parameters. In other to run the code, you have to add 2 more constructor, one with 0 parameter, and one with 3 parameters.
public Car() {
}
public Car(String b, int year, int price) {
yearModel = year;
brand = b;
priceModel = price;
}
public Car() {
}
public Car(String b, int year, int price,) {
yearModel = year;
brand = b;
priceModel = price;
}
In that case you have a constructor that has 4 parameters.

Categories

Resources