The Question is:
1) How can i get subclass parameter values to superclass?
2) i want to take the name(From subclass) for collection.sort , like this.model.compareTo(other.model). However, I don't know how to get the "Name" Value from subclass and do the collection.sort.
** Is it correct to write public int compareTo(Car other, Taxi other2)??? **
Here is the code:
public class Car implement comparable <Car>()
{
private string model;
private int price;
public car(String model , int price)
{
this.model=model;
this.price=price;
}
............some getmethod here..........
public int compareTo (Car other)
{
** Want to sort by name , like this.model.compareTo(other.model)**
}
}
Taxi.java:
public class taxi extends Car ()
{
private string name;
public taxi (String model , int price, String name)
{
super(model, price);
this.name = name;
}
......some getmethod here..........
}
you can use subclass values by creating object of sub class in superclass.
It is also known as delegation.
Related
I have the following interface:
public interface IStaff {
public StaffPosition getPosition();
public String toString();
}
and the class:
public class Worker implements IStaff {
private String name = null;
private String surname = null;
private int age = 0;
//StaffPosition is an enumeration class
private StaffPosition position= null;
public Worker (String name, String surname, int age, StaffPosition position){
this.name = name;
this.surname= surname;
this.age= age;
this.position= position;
}
#Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(this.name);
buffer.append(" ");
buffer.append(this.surname);
return buffer.toString();
}
#Override
public StaffPosition getPosition() {
return this.position;
}
public int getAge(){
return this.age;
}
In another class - Building, I have a HashMap<Office, IStaff> officeswhere Office is a normal class which only holds the number of the office and has a getter for that number.
And then in a yet another class Company I have an ArrayList<Building> buildings, which holds information about all the buildings of a company. In this class I need to get the age of a worker but how can I do that? So far I have a loop like this to get to the map:
for (Building building: buildings) {
for (Map.Entry<Office, IStaff> office: building.offices.entrySet()) {
//get the age of a worker
}
}
Is there a way to do that?
The only real answer is: when you need such an information in places where only your interface should show up, then that information needs to sit on the interface.
So your interface could have a method getAge(), or maybe getBirthday().
Side notes:
using I for "interface" in class names ... is bad practice, or at least: very much against java conventions.
you don't need to have a toString() in your interface. You get one from Object anyway.
(of course, there are dirty tricks, like doing an instanceof check somewhere, and then casting to the type of the concrete class. But as said: that is really bad practice)
Make IStaff an abstract class and then call the method.
UML Diagram
I am brand new to Java, though I've taken other programming courses. I'm really struggling with the class concept from a UML diagram. I have a parent class and two child classes. My assignment is to create this class structure. I am struggling with the concept of class and relationships in general though.
Example: If my parent class is "Animal" and my child classes are "Monkey" and "Bear" - if the only choices that will be implemented are "Monkey" and "Bear", this makes the class "Animal" an abstract class distinction as there will never be just "Animal", it will always be a "Monkey" or a "Bear".
So, how would I create three files (Animal.java, Monkey.java, Bear.java) if Animal is abstract? I understand that the properties and traits of Animal are inherited by Monkey and Bear. Assuming that I have, for instance, name and age of the animal as attributes and getters and setters for each - if name and age of "Animal" class are private (code below), how does "Bear" class pick up the name and age if it is in its own java file/class? My code is below...
Animal.java
public class Animal {
private String animalName;
private int animalAge;
public void setName (String name) {
animalName = name;
}
public void setAge (int age) {
animalAge = age;
}
public static String getName() {
return animalName;
}
public static String getAge() {
return animalAge;
}
}
Bear.java
public class Bear {
public int weight;
public static int weight() {
return weight;
}
}
// This is where I get stuck & don't know where to go from here.
I understand that I am creating an object "Bear" which is part of the class "Animal", but as Bear is its own class, how does "Bear" get its assigned values from Animal? I can assign "Animal" and "Bear" with default values, but my brain cannot put together how they're talking to one another.
This might be outside the scope of this forum but my professor is unresponsive and I've read through books, ebooks, the course material, and several lectures and this is just not coming to me and I'm two weeks behind at this point trying to understand this concept so I can move forward with the actual code in the program.
Thanks in advance.
You forgot to do this:
public class Bear extends Animal {
// ...
}
I would recommend that you add constructors:
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() [ return this.name; }
public int getAge() { return this.age; }
}
public class Bear extends Animal {
private int weight;
public Bear(String name, int age, int weight) {
super(name, age);
this.weight = weight;
}
public int getWeight() { return this.weight; }
}
You can do this, because Bear IS-A Animal:
Animal b = new Bear("Smokey", 10, 300);
System.out.println(b.getName()); // prints "Smokey"
Apologies if the question has been asked before, though I did look around and couldn't find an applicable answer to my specific problem. Anyway, I'm trying to model a store that sells desserts which are all derived from a specific Dessert superclass.
When I try to run the program to test my classes, I get an error say "Cookie is not abstract and does not abstract method getPrice() in Dessert public class Cookie extends Dessert. I am getting the same error with another class called Fruit, but it is more or less the exact same as Cookie just with some different member variables and method names.
Here is the Dessert superclass:
public abstract class Dessert {
/** Name of the dessert item. */
protected final String name;
/**
* Constructs a new dessert item.
* #param name Name of the dessert.
*/
public Dessert(String name) {
this.name = name;
}
/**
* Get name of the dessert.
* #return dessert name
*/
public final String getName() {
return name;
}
/**
* Get the price of the dessert.
* #return Dessert price
*/
public abstract double getPrice();
}
And here is the Cookie subclass:
public class Cookie extends Dessert {
private int number;
private double price;
public Cookie (String name, int number, double price) {
super(name);
this.number = number;
this.price = price;
}
public int getItemCount() {
return number;
}
public double getPricePerDozen() {
return (price / 12) * number;
}
}
I can't seem to get the formatting right, but the lines immediately following the colons should be a part of the code block. As well as the curly braces following the block.
Thanks in advance for the help!
Since Cookie.java extends Dessert.java and the latter has an
abstract method getPrice()
Cookie.java must provide a definition for it. (Unless it itself is abstract.
One would do that if we had things such as OatmealCookie
ChocolateChipCookie that would be the definite class.)
I retyped the material quickly due to the problems git markdown and got
these to compile. I assume that the price for Cookie should simply be the
price per dozen and added the appropriate definition to it:
public abstract class Dessert {
protected final String name;
public Dessert (String name) {
this.name = name;
}
public final String getName() {
return name;
}
public abstract double getPrice ();
}
public class Cookie extends Dessert {
private int number;
private double price;
public Cookie (String name, int number, double price) {
super (name);
this.number = number;
this.price = price;
}
public int getItemCount() {
return number;
}
public double getPricePerDozen() {
return (price/12) * number;
}
public double getPrice() {
return getPricePerDozen();
}
}
Your Dessert class has an abstract method double getPrice(), and Cookie extends it, so Cookie needs to implement getPrice() or also be abstract in order to get rid of this error.
The code obviously doesn't compile in its current state, but think of it this way - If we were to instantiate a Cookie, its double getPrice() method is inherited from its super class Dessert, so the method would exist to be called, but it has no implementation in either Cookie or Dessert, so the result of calling it would be unspecified. Java sees this at compilation time, and so prevents you from trying to generate code that is ill-defined.
I have an Arraylist with type Person. Name is a class that I have created. In my mainapp I'm creating some Name objects, setting each name-object to a person object and then adding the person objects to an ArrayList. When I try to sort the list using Collections.sort(), I get a ClassCastException.
I can not see what the problem is.
Here is my code so far:
public class Person<T> implements Comparable<Person<T>> {
private T name;
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
#Override
public int compareTo(Person<T> o) {
return ((Person<T>) this.getName()).compareTo((Person<T>) o.getName());
}
}
The return value from getName() has type T, but you are trying to cast it to Person<T>. To fix the problem, you need to compare the names directly without casting:
public int compareTo(Person<T> o) {
return this.getName().compareTo(o.getName());
}
Now this will cause another error because the compiler doesn't know if T has the compareTo() method. To fix that, you need to add a bound to the type T:
public class Person<T implements Comparable<T>> implements Comparable<Person<T>>
Note:
To me, this seems like overuse of generics. Why should name be allowed a generic type when String is the only natural fit? And why do you need a Name class? It is likely only a wrapper around a String so you should just use String directly.
You are casting this.getName(), which is of type T, to type Person<T>. I.e. you are casting a Name to a Person, hence the ClassCastException ("name is not a person").
To fix this, please remove the casts and compare the names directly. Ignoring null-safety, it would be:
return getName().compareTo(o.getName());
Note that class Name also needs to implements Comparable<Name>.
Why is your name a type? This looks a bit weird. Could it be you meant to do something like this:
public class Person implements Comparable<Person> {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int compareTo(Person other) {
return this.name.compareTo(other.getName());
}
}
I'm newbie in Java. So question might sound simple, but I'm stuck and can not figure out why this code returns null and 0.0 ?
file: Transport.java
public class Transport {
private String name;
private double price;
public Transport(String name, double price) {
this.name = name;
this.price = price;
}
public String carName() {
return name;
}
public double carPrice(){
return price;
}
}
file: Car.java
public class Car extends Transport{
protected String name;
protected double price;
public Car(String name, double price) {
super(name, price);
}
#Override
public String carName(){
return name;
}
#Override
public double carPrice(){
return price * 1.5;
}
}
file: Main.java
public class Main {
public static void main(String[] args) {
Car c = new Car("CarBrand", 1000);
System.out.println("Name: " + c.carName());
System.out.println("Price: " + c.carPrice());
}
}
Output
Name: null
Price: 0.0
You've declared separate name and price variables in Car, and never assigned a value to them - they're not the same as the name and price variables declared (and initialized) in Transport. So you're seeing the default values for String and double, basically. Get rid of those extra variables in Car, and use super.carPrice() to get the original price from Transport:
public class Car extends Transport {
public Car(String name, double price) {
super(name, price);
}
#Override
public double carPrice(){
return super.carPrice() * 1.5;
}
}
Note that there's no need to override carName() at all unless you really want it to change behaviour.
I'd also suggest changing carName() and carPrice() to getName() and getPrice() to be more idiomatic.
You are passing both the values to parent class Transport through super(). So
Car c = new Car("CarBrand", 1000);
will eventually set
Transport class attributes name & price.
You dont need to declare both the attributes in Car class. Car will have both attributes implicitly through inheritance. Here you are creating separate attributes for Car.
The problem is that you have two different variables for name, one in Car and one in Transport. c.carName() returns Car.name which has not been initialized.
If your car class is the one below, it will work
public class Car extends Transport {
public Car(String name, double price) {
super(name, price);
}
#Override
public double carPrice(){
return price * 1.5;
}
}
the same goes for the variable price
The derived class Car is hiding the instance variables of class Transport .So although you are inheriting the correctly initialized data members from Transport class ,but the Car class instance variables initilized to their default values are getting returned from Car class methods
When you create the 'c' object of type Car, you assign values only for 'name' and 'price' variables of class Transport (because in your constructor you call super(name, price) that will call the constructor from your Parent class).
Here: c.carName() you call the method from your Car class (because is marked as #Override) and this one returns the value of the 'name' variable from class Car. And this variable in your case, is null because you didn't assign any value for it yet.
You assigned the value "CarBrand" for 'name' variable of type Transport.
The same for 'price' variable.
The use of super will return the values which you already stored in the parent class by calling the constructor super(name, price), the use of super followed by dot notation will access the parent class method. So super.carPrice() will return the value stored in the parent class.
Also, #Override annotation should only used to change an existing method from the parent class with a new functionality in the child class with out changing the name. So in case of the #Overide for carname() you need to call the super.carname() because you are returning the value from the parent class.
In short, The reason why you are getting null and 0.0 because you are accessing the child class values when you should be accessing the parent class values.
public class Car extends Transport{
protected String name;
protected double price;
public Car(String name, double price) {
super(name, price);
}
#Override
public String carName(){
return name;
}
#Override
public double carPrice(){
return price * 1.5;
}
}
Your class should be
public class Car extends Transport{
public Car(String name, double price) {
super(name, price);
}
public String getName(){
return super.carName();
}
#Override
public double carPrice(){
return super.carPrice()* 1.5;
}
}
your main class should now be
public class Main {
public static void main(String[] args) {
Car c = new Car("CarBrand", 1000);
System.out.println("Name: " + c.getName());
System.out.println("Price: " + c.carPrice());
}
}