I am learning java. I would like to have a enum as a parameter in my constructor. But I am getting an error
(I have my enum in a separate class that is public and named AvailabilityState {AVAILABLE,ORDERED,REMOVED }
public class Facultymember extends User {
private int MAX_GENERALBOOKS = 5;
private int MAX_AUDIOBOOKS = 2;
private AvailabilityState aStatus;
public Facultymember(int genbook, int audbook,AvailabilityState aStatus ){
this.MAX_GENERALBOOKS=genbook;
this.MAX_AUDIOBOOKS=audbook;
this.aStatus = aStatus;
}
#Override
public String toString() {
return "Facultymember {" + "MAX_GENERALBOOKS=" + MAX_GENERALBOOKS+ ", MAX_AUDIOBOOKS =" + MAX_AUDIOBOOKS + "AvailabilityState," + aStatus + '}';
}
}**
If you require a parameter of type AvailabilityState, you should provide it, like so:
User availableFaculty = new Facultymember(5,2, AvailabilityState.AVAILABLE);
User orderedFaculty = new Facultymember(5,2, AvailabilityState.ORDERED);
User removedFaculty = new Facultymember(5,2, AvailabilityState.REMOVED);
Alternatively, define another constructor with default availability state:
public Facultymember(int genbook, int audbook) {
// assuming availability by default
this(genbook, audbook, AvailabilityState.AVAILABLE);
}
Related
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 + ".";
}
}
I was wondering, whether it would be possible to assign a unique ID for every new class (not instance!).
Example of what I mean:
public class ChildObjectOne extends SuperClass {}
public class ChildObjectTwo extends SuperClass {}
public SuperClass {
private final int ID;
public SuperClass() {
this.ID = newID();
}
}
final ChildObjectOne childObjectOne = new ChildObjectOne();
final ChildObjectTwo childObjectTwo = new ChildObjectTwo();
System.out.println(childObjectOne.getID()); //prints 1
System.out.println(childObjectOne.getID()); //prints 2
childObjectOne = new ChildObjectOne();
childObjectTwo = new ChildObjectTwo();
System.out.println(childObjectOne.getID()); //prints 3
System.out.println(childObjectOne.getID()); //prints 4
What I want it to do instead is print 1 and 2 again. It should generate a new ID for every new class, but if I create a new instance of that class, I want the ID to stay the same.
I tried to achieve this using generics:
public SuperClass<T> {
private static int ID;
public SuperClass() {
this.ID = newID();
}
}
public class ChildObjectOne extends SuperClass<ChildObjectOne> {}
public class ChildObjectTwo extends SuperClass<ChildObjectTwo> {}
I was hoping, it would count passing a different T as a new class, but that didn't work. Instead the ID is the last one that was set.
How can I achieve this kind of ID system?
To expand upon my comment, the class name will give you an unique String ID. If you want that ID to be a number you could do something like this:
class IdGenerator{
private static int counter = 0;
private static HashMap<String,Integer> classIdMap = new HashMap<>();
public static synchronized int getId(Class clazz){
if (classIdMap.containsKey(clazz.getName())) {
return classIdMap.get(clazz.getName());
} else {
classIdMap.put(clazz.getName(), ++counter);
return counter;
}
}
}
And then from your class you would do:
IdGenerator.getId(this.getClass());
The generated IDs might not be the same every time you run your app, depending on how it is structured.
For example:
Scanner in = new Scanner(System.in);
if (in.nextInt() < 100) {
System.out.println("a = " + new Aclass().id); // a = 1
System.out.println("b = " + new Bclass().id); // b = 2
} else {
System.out.println("b = " + new Bclass().id); // b = 1
System.out.println("a = " + new Aclass().id); // a = 2
}
Class::getName
Each class in Java already carries a unique identifier: the fully-qualified name of the class. No need for you to add an identifier.
Access the fully-qualified name by calling Class::getName.
For a class:
String.class.getName()
"java.lang.String"
For an object (an instance), call Object::getClass, and then Class::getName.
customer.getClass().getName()
com.example.invoicing.Customer
i created 2 classes and i want to use Class A in the methode of class B
created class A
i use protected because i created a superclass in my code, dont mind it
public class A {
protected String modulname;
protected String verantwortliche;
protected int sws;
protected int credits;
public A ( String modulname, String verantwortliche, int sws, int credits ){//beginning of the methode of class A
this.modulname =modulname;
this.verantwortliche = verantwortliche;
this.sws= sws;
this.credits = credits;
}
public class B {
private String pruefer;
private double leistungeninprozent;
//i want to use the Attributes/Constructors form class A in the class B
//an put it like this:
public B (class A, String pruefer, double
leistungeninprozent){
this.leistungeninprozent = leistungeninprozent;
this.modul = modul;
this.pruefer = pruefer;
}
change this:
public B (class A, String pruefer, double
leistungeninprozent){
this.leistungeninprozent = leistungeninprozent;
this.modul = modul;
this.pruefer = pruefer;
}
to this:
public B (A aObject, String pruefer, double //change "class A" to "A aObject"
leistungeninprozent){
this.leistungeninprozent = leistungeninprozent;
this.modul = modul;
this.pruefer = pruefer;
}
then you can access it in the B constructor like this: aObject.modulname
Beautiful it worked. And how do I implement the toString methode?
I mean implement the toString of class A into the toString of class b.
Thats the toString form class A:
#Override
public String toString() {
return "Module [Modulname=" + modulname + ", Verantwortliche=" + verantwortliche + ", SWS=" + sws
+ ", Credits=" + credits + "]";
}
That is the toString methode from class B:
#Override
public String toString() {
return "Leistungen [Pruefer=" + pruefer + ", LeistungeninProzent=" + leistungeninprozent
+ "]";
}
Now i want to make only one toString methode from the two different classes.
At this very early point in the process of learning Java, I would advise avoiding the use of nested classes. An instance of B can only exist within an instance of class A.
To answer your question, a parameter should represent an instance of a class, not the class itself. Which then becomes a local variable within the method, and through which you can access its fields and methods.
Let's say you got a class x with a method copy().
This method copy() gets a class y as a param. copy(y test).
My question is, how do I make a new object out of the class that's sent as param just like this:
public void copy(y villy){
villy v = new villy();
}
You should consider that the y class is a parent one, and that I'll be passing as params its childs aswell, so what that method should do is creating a new object of the class that's sent as param!
If the parameter is a Class reference, and the class has a public constructor with no parameters:
public void copy(Class cls){
Object obj = cls.newInstance();
}
If the parameter is some object implementing the Cloneable interface, and another object of the same class is required:
public void copy(Cloneable obj1){
Object obj2 = obj1.clone();
}
EDIT 20.01.2016
So I assume that every object is a Pokemon, which has some abilities, and it has a method copy used to copy the abilities of another Pokemon. Then I would do it like this:
public class FET {
public static void main(String[] args){
Pokemon aerodactyl = new Pokemon (new Ability[]{ Ability.WALK, Ability.FLY });
Pokemon golduck = new Pokemon (new Ability[]{ Ability.WALK, Ability.SWIM });
System.out.println ("aerodactyl = " + aerodactyl);
System.out.println ("golduck = " + golduck );
System.out.println ();
golduck.copy (aerodactyl);
System.out.println ("aerodactyl = " + aerodactyl);
System.out.println ("golduck = " + golduck ); // golduck has now the same abilities as aerodactyl
System.out.println ();
aerodactyl.abilities[0] = Ability.EXPLODE; // change aerodactyl's abilities
System.out.println ("aerodactyl = " + aerodactyl);
System.out.println ("golduck = " + golduck ); // abilities of aerodactyl have changed but golduck's not
System.out.println ();
}
}
enum Ability {
WALK,
FLY,
SWIM,
TALK,
EXPLODE
}
class Pokemon {
public Ability[] abilities;
public Pokemon (Ability[] abilities) { // constructor
this.abilities = abilities;
}
public void copy (Pokemon p) { // copy abilities of another Pokemon
abilities = (Ability[]) p.abilities.clone();
}
public String toString() { // string representation of Pokemon
String str = "Pokemon";
if (abilities != null) {
for(int i = 0; i < abilities.length; i++) {
str += (i==0) ? ": " : ", ";
str += abilities[i];
}
}
return str;
}
}
I am writing a program to simulate a parking ticket system. In total I 4 distinct classes, these being ParkedCar, ParkingMeter, ParkingTicket and PoliceOfficer. In my PoliceOfficer class I have an if statement to determine if the police officer should issue a ticket for the parked car.
I have the following statement to do such: return new ParkingTicket(this,car,meter). I get an incompatible type error. If I need to post my code for my other classes, let me know.
Parking Ticket Class:
import java.text.DecimalFormat;
public class ParkingTicket {
private static int ticketCount;
private ParkedCar car;
private PoliceOfficer officer;
private ParkingMeter meter;
private double fine;
public final double BASE_FINE = 25.0;
public final double HOURLY_FINE = 10.0;
public ParkingTicket (ParkedCar aCar, PoliceOfficer anOfficer, ParkingMeter aMeter) {
this.car = aCar;
this.officer = anOfficer;
this.meter = aMeter;
calculateFine();
}
public void calculateFine() {
// Calculate fine & increment ticket count
++ticketCount;
int timeOver = (int)Math.ceil((car.getMinutesParked() - meter.getMinutesPurchased() / 60.0));
fine = BASE_FINE * HOURLY_FINE * (timeOver - 1);
}
public String toString() {
DecimalFormat newDecimal = new DecimalFormat("$###.00");
return "Ticket Number: " + ticketCount + "\n" +
car + "\n" + meter + "\n" + "Fine: " + newDecimal.format(fine) + "\n"
+ officer;
}
}
Police Officer Class:
public class PoliceOfficer {
// Declare data fields
private String name;
private String badgeNumber;
// Default constructor
public PoliceOfficer (String name, String badgeNumber) {
this.name = name;
this.badgeNumber = badgeNumber;
}
// Copy of PoliceOfficer
public PoliceOfficer (PoliceOfficer OfficerCopy) {
this.name = OfficerCopy.name;
this.badgeNumber = OfficerCopy.badgeNumber;
}
// Class to check a parked car and determine if the
// cars time has expired
public ParkingTicket check(ParkedCar car, ParkingMeter meter) {
if (car.getMinutesParked() > meter.getMinutesPurchased()) {
// Creating a new object of ParkingTicket object
return new ParkingTicket(this,car,meter);
} else {
return null;
}
}
// toString class
public String toString() {
return "Officer Name: " + name + "/n" + "Badge ID: " + badgeNumber;
}
}
You've just got your arguments reversed. The ParkingTicket constructor requires its arguments to be:
(ParkedCar, PoliceOfficer, ParkingMeter)
But you're passing
(PoliceOfficer, ParkedCar, ParkingMeter)
All you need to do is change the call to new ParkingTicket(car, this, meter).
You mention instantiating ParkingTicket in PoliceOfficer (so this is PoliceOfficer)
new ParkingTicket(this,car,meter)
I believe it should be
new ParkingTicket(car,this,meter)
Because the constructor signature is ParkingTicket(ParkedCar, PoliceOfficer, ParkingMeter)