Finding Java an overly complicated language. I can't figure out this association thing if my life depended on it. I'm specifically stuck on the Cab object +pickup(rider:Passenger): String. I know it will return a String and here's the code I have so far.
UML Diagram
package cabsimulation;
public class Cab {
private double companyTotalFare;
private double rate;
private double taxiTotalFare;
private int tripCounter;
private int cabID;
public Cab(int cabID){}
public double dropOff(int minutes){
return minutes*rate;
}
public double endOfShift(){
double sumOfFares = taxiTotalFare + companyTotalFare;
return sumOfFares;
}
//public String report();
public double getRate(){
return rate;
}
public void setRate(double cabRate){
this.rate = cabRate;
}
}
and
public class Passenger {
private final double weight;
private final boolean inFrontSeat;
public Passenger (double weight, boolean front){
this.weight = weight;
this.inFrontSeat = front;
}
public double getWeight(){
return weight;
}
public boolean isInFrontSeat(){
return inFrontSeat;
}
}
How do I write (program) an association between these two objects?
As written in your instructions: define a typed attribute
private Passenger passenger;
or the like (I'm no Java guy).
When you want to have an association between two classes, you will normally use an instance variable. In this case, a Cab can contain a Passenger. So you want to have an instance variable in the Cab class which is able to hold a Passenger. This can be done like that:
public class Cab {
Passenger passenger;
//...
}
In the pickUp method shown in the UML, you want to fill this variable, e. g. like that (unfortunately, there is no specification what String the method should return):
public class Cab {
Passenger passenger;
//...
public String pickUp(Passenger rider) {
this.passenger = rider;
return "something";
}
}
After you called the method pickUp, you can access the passenger in the cab via its instance variable.
I hope I could help you!
usually, if you have an attribute, you have the getter/setter which are dedicated to set and to get the attribute.
If you have a method (other than a setter) with a parameter of the type of an attribute, it does not mean that the parameter will set the attribute.
So for me, it could be easier to remove the method pickup and to define a getter and setter on passenger.
Related
no idea if this is possible, cant seem to find an answer online so here it goes.
I'm modeling an ad bidding platform in java, where advertisers submit offers to show ads on a site and the highest bid wins.
I created a Bid object(Which contains the price offered, ad url, and name of the bidder for tracking) and an Auction object that's really just a TreeMap of prices(as ints) and Bids (as Bid objects).
I know this is a super rudimentary look at such a thing, but is it possible to have the Bid object constructor add the Bid to the Auction? Just to stick to DRY principles? If not possible from the constructor, is there somewhere else I can automate this outside of the Main method?
Bid.class
public class Bid {
private int cents;
private String location;
private String bidServer;
public Bid(int cents, String location, String bidServer) {
this.cents = cents;
this.location = location;
this.bidServer = bidServer;
}
public int getCents() {
return cents;
}
public String getLocation() {
return location;
}
public String getBidServer() {
return bidServer;
}
}
Auction.class
import java.util.Map;
import java.util.TreeMap;
public class Auction {
private Map<Integer, Bid> bids ;
public Auction() {
this.bids = new TreeMap<>();
}
public void addBid (Bid bid){
bids.put(bid.getCents(), bid);
}
public Bid getHighestBid(){
return bids.get(((TreeMap<Integer, Bid>) bids).lastKey());
}
public void clearBids(){
bids.clear();
}
}
Change the method addBid in Auction:
public void addBid(int cents, String location, String bidServer) {
Bid bid = new Bid(cents, location, bidServer);
bids.put(cents, bid);
}
You could put Auction and Bid in the same package and make the constructor of Bid package-private.
Also, you should declare bids like this:
private SortedMap<Integer, Bid> bids;
In that case you can write method getHighestBid like this:
public Bid getHighestBid() {
return bids.get(bids.lastKey());
}
You could pass the Auction object when you construct the bid and then just add the Bid as this like so:
public Bid(int cents, String location, String bidServer, Auction auction) {
this.cents = cents;
this.location = location;
this.bidServer = bidServer;
auction.addBid(this);
}
Here's are two classes, Passenger and Car. Instead of initializing all private members of the Car class in all constructors, I thought of setting default values for them and overwriting specific members' values if provided by the instance creator.
import java.util.ArrayList;
class Passenger {
private String name;
Passenger(String name) {
this.name = name;
}
}
class Car {
private String color = "red";
private int numberOfWheels = 4;
private ArrayList<Passenger> passengers = new ArrayList<Passenger>();
Car() {}
Car(String color) {
this.color = color;
}
Car(int numberOfWheels) {
this.numberOfWheels = numberOfWheels;
}
public void addPassenger(Passenger p) {
this.passengers.add(p);
}
}
Is it safe to set default values to class members like this? Any pitfalls to avoid for any particular data types (even other than the ones I have used)?
Yes, it is safe.
Personally I prefer initialize where is declaration if is a common value for all constructors. If I have more constructor is not very pleasure to write that thing multiple times. And for me is more clear what value have.
Let say, I have a student, employee and car class in a different structure in JSON file.
I already parse them and put the respective data to its POJO classes. The things is I wanna display data to inside a recycler view.
But here I have common field both three class is name and weight.
So, I wanna pass to list of generic to recycler view and populate them by calling like this:
tvName.setText(Object(should be generic).getName());
tvWeight.setText(Object(should be generic).getWeight());
It should display name and weight all the student, employee and car .
RecyclerView looks like
---------------------------------------------------------
CarName
CarWeight
---------------------------------------------------------
EmplyoeeName
EmplyoeeWeight
---------------------------------------------------------
StudentName
StudentWeight
---------------------------------------------------------
EmplyoeeName
EmplyoeeWeight
---------------------------------------------------------
CarName
CarWeight
---------------------------------------------------------
CarName
CarWeight
---------------------------------------------------------
StudentName
StudentWeight
Any idea would be highly appreciated.
In order to achieve that, you need something called polymorphism, learn more from StackOverflow, Java Docs and Wikipedia. In order to respect that pattern I would implement the problem like this:
I would create an Interface that has the methods you need:
public interface AttributesInterface {
String getName();
double getWeight();
}
Then I would make every POJO class implement that interface, looking in the end like this:
public class Car implements AttributesInterface {
private String name;
private double weight;
#Override
public String getName() {
return null;
}
#Override
public double getWeight() {
return weight;
}
}
In the adapter you store the list like this. If a class will implement the interface, then you will be able to add it in that array. So you will have an array that will contain Student, Car, Employee in the same time.
private List<AttributesInterface> list = new ArrayList<>();
Then final step is in onBindViewHolder where you get an object from that array and set the corresponding values.
AttributesInterface object = list.get(position);
tvName.setText(object.getName());
tvWeight.setText(String.valueOf(object.getWeight()));
Also, you mentioned that you want a solution to work with multiple classes. As long as you implement the interface in each class that needs to be displayed, you can have a million classes.
You can create only one POJO class and you can add extra variable say type. So your POJO class will look like below.
public class MyClassModel {
private String type=""; // S=Student, C=Car, E=Employee
private String name="", weight="";
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
Now you will get type in your RecyclerviewAdapter so you can write your logic according to type of data.
I need help fixing my code with the basic concepts listed above. To save from clutter, I took a screen shot of the directions here: https://imgur.com/SdiotUi
However, when I run my code it isn't working. I know there are a lot of errors but I'm having trouble fixing them even though I've spent the past few hours googling the correct way to do this.
When I create the first constructors I am not sure if I am assigning the name and legs correctly, I am having trouble returning "true", I get an error calling the parent class taking one argument, and I don't think I am overriding the abstract class correctly.
My code:
public class Animal1 {
private String animalName;
public int numberOfLegs;
public Animal1(String name){
name = animalName;
name = "John";
}
public Animal1(String name, int legs){
name = animalName;
legs = numberOfLegs;
name = "Jack";
legs = 4;
}
public String getName(){
return animalName;
}
public int getLegs(){
return numberOfLegs;
}
public void isAMammal(){
return true;
}
public void isCarnivorous(){
return true;
}
public abstract class getHello{
}
}
public class Cat1 extends Animal1{
public Cat1(String name){
Animal1.name;
}
public abstract class getHello{
return "Meow";
}
}
public class Dog1 extends Animal1{
public Dog1(String name){
Animal1.name;
}
public abstract class getHello{
return "Woof";
}
}
public abstract class Animal1 { // If you want to have an abstract method, declare the class as abstract
private final String animalName;
private final int numberOfLegs; // better of using private and make it final since it's not going to change.
public Animal1(final String name, final int legs){ //better making the input parameters final since they are not supposed to be changed
//name = animalName;
//legs = numberOfLegs;//it assigned the field to an input parameter. that will take no effect on the object created.
animalName = name;
numberOfLegs = legs;
}
public String getName(){
return animalName;
}
public int getLegs(){
return numberOfLegs;
}
public boolean isAnimal(){ //boolean function needs a return type too!!
return true;
}
public boolean isCarnivorous(){
return true;
}
public abstract String getHello(); // an abstract method has same requirement as a normal method besides the abstract modifier. it will need a return type. And it ends with a semicolon
}
public class Cat1 extends Animal1{
public Cat1(final String name){
super(name, 4); //use super to call parent constructor
}
#Override
public String getHello(){
return "Meow";
}
}
public class Dog1 extends Animal1{
public Dog1(final String name){
super(name, 4);
}
#Override
public String getHello(){
return "Woof";
}
}
First, it looks like a few of your methods are declared as classes. I assume you wanted to make them abstract methods. They need to be changed to:
public abstract String getHello();
Note that abstract methods can only be declared in an abstract class. So, you need to redefine Animal1 as abstract.
public abstract class Animal1
Next, when you implement the abstract method, you define it as
public String getHello()
If you are using an IDE like Eclipse it will automatically offer to generate this method.
Finally, when using your constructor in your child classes like Cat1, you are trying to set "name" as if it was a static variable and bypassing the constructor you already had set for Animal1. The best way to correct this is to change the constructor in Cat1 and Dog1 to call the super constructor.
public Cat1(String name){
super(name);
}
Do forgive me if the title is not correct, I thought this very question has to with "Polymorphism" but didn't want to complicate the title.
I am learning Java and following "Java: Learn to Program", As I am going along, I am applying the knowledge and creating my own scenarios to see
how "Polymorphism" is applied. I would appreciate it if someone can help me understand how to do this task. I have three classes:
Abstract Employee
Manager (Subclass of Employee)
Restaurant
Employee class and Manager class are pretty straight forward. I am trying to create a restaurant and every restaurant has a manager. My question is:
Should I pass "Manager" type as constructor arguments of "Restaurant" class or instantiate the "Manager" object in the constructor?
public abstract class Employee{
private String _empName;
private double _empSalary;
public Employee( string name, double salary){
_empName = name;
_empSalary = salary;
}
public void setEmpName( String name ){
_empName = name;
}
public String getEmpName(){
return _empName;
}
public void setEmpSalary( double salary ){
_empSalary = salary;
}
public double getEmpSalary(){
return _empSalary;
}
}//CLASS
public class Manager{
private double _yrsOfExp;
public Manager( String name, double salary, double experience ){
super(name, salary);
_yrsOfExp = experience;
}
public void setManagerExperience( double years ){
_yrsOfExp = years;
}
public double getManagerExperience(){
return _yrsOfExp;
}
}//CLASS
This is where I need help, I am declaring the constructor with "MANAGER TYPE". Should I be declaring the instance of "Manager" with the construction instead of
passing "Manager type" with the constructor, please?
public class Restaurant{
private Manager _manager;
private String _location;
//CONSTRUCTOR 1
//SHOULD I PURSUE IT THIS WAY OR
public Restaurant( Manager manager, String location){
_manager = manager;
_location = location;
}
//CONSTRUCTOR 2
//SHOULD I DO IT THIS WAY?
public Restaurant( String name, double salary, double experience, String location){
super(name, salary, experience);
_location = location;
}
public String toString(){
String str = "";
return str;
}
}//CLASS
This is partly a matter of taste and of what else you're going to do with the objects.
If you may ever want to refer to Managers independently, then they want to be their own object rather than properties of the Restaurant.
Since a Restaurant is not itself a Manager, I would suggest that it shouldn't take a Manager's properties in its constructor, and should instead have a Manager assigned to it (either in the constructor or in a setManager() call).
Among other things, that will make much more sense if one Manager is ever in charge of two Restaurants.