java print arraylist of interface - java

I'm learning observer design pattern from one of youtube videos and want to understand a bit more the behavior of interface arraylist, I think I quite understand how it works but when it comes the interface arraylist, its confusing to me how to access the value inside loop.
the subject and observer interfaces as follow;
public interface Subject {
public void register(Observer o);
public void unregister(Observer o);
public void notifyObserver();
}
public interface Observer {
public void updateViaObserver(double ibmPrice, double aaplPrice, double googPrice);
}
package observer_pattern;
import java.util.ArrayList;
import java.util.Arrays;
public class StockGrabber implements Subject{
private ArrayList<Observer> observers;
private double ibmPrice;
private double aaplPrice;
private double googPrice;
public StockGrabber(){
// Creates an ArrayList to hold all observers
observers = new ArrayList<Observer>();
}
public void register(Observer newObserver) {
observers.add(newObserver);
}
public void notifyObserver() {
for(Observer observer : observers){
observer.updateViaObserver(ibmPrice, aaplPrice, googPrice);
}
}
public void setPrice(double newIBMPrice, double newAAPLPrice, double newGOOGPrice){
this.ibmPrice = newIBMPrice;
this.aaplPrice = newAAPLPrice;
this.googPrice = newGOOGPrice;
notifyObserver();
}
}
package observer_pattern;
public class StockObserver implements Observer {
private double ibmPrice;
private double aaplPrice;
private double googPrice;
private Subject stockGrabber;
public StockObserver(Subject stockGrabber){
this.stockGrabber = stockGrabber;
this.observerID = ++observerIDTracker;
stockGrabber.register(this);
}
// Called to update all observers
public void updateViaObserver(double ibmPrice, double aaplPrice, double googPrice) {
this.ibmPrice = ibmPrice;
this.aaplPrice = aaplPrice;
this.googPrice = googPrice;
// this works
printThePrices();
// doesn't work
toString();
}
public void printThePrices(){
System.out.println(observerID + "\nIBM: " + ibmPrice + "\nAAPL: " +
aaplPrice + "\nGOOG: " + googPrice + "\n");
}
public String toString() {
return "StockObserver: ibmPrice=" + ibmPrice + " aaplPrice=" + aaplPrice;
}
}
MAIN
package observer_pattern;
public class GrabStocks{
public static void main(String[] args){
StockGrabber stockGrabber = new StockGrabber();
StockObserver observer1 = new StockObserver(stockGrabber);
stockGrabber.setIBMPrice(197.00);
stockGrabber.setAAPLPrice(677.60);
stockGrabber.setGOOGPrice(676.40);
observer1.toString();
}
}
How to access value for my ArrayList<Observer> observers inside "notifyObserver" method? if I do this System.out.println(observers.get(0)); I get observer_pattern.StockObserver#446cdf90

How to access value for my ArrayList observers inside "notifyObserver" method?
You're already doing it.
public void notifyObserver() {
for(Observer observer : observers){
observer.updateViaObserver(ibmPrice, aaplPrice, googPrice);
}
}
if I do this System.out.println(observers.get(0)); I get observer_pattern.StockObserver#446cdf90
That's because your StockObserver class does not have a toString method that returns a human readable representation of the object. Something like this
public String toString() {
return "StockObserver: ibmPrice=" + ibmPrice + " aaplPrice=" + aaplPrice;
}

Related

"Triangle 1 is abstract; Cannot be instantiated" Driver error

Coming across problems with not being able to to be instantiated even extending and trying to override it does nothing to fix it. Trying with a driver file and 2 other files to print results back. Been stuck for awhile, anything is appreciated at this point.
public abstract class Triangle extends Lot
implements Comparable< TestTriangle> {
public abstract double calculateArea();
public abstract String getID();
public int compareTo(LotType1 o) {
if (calculateArea() > o.calculateArea()) {
return 1;
} else if (calculateArea() < o.calculateArea()) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return "Lot ID: " + getID()
+ " Area: " + calculateArea();
}
}
Driver File =====
public class TestLots {
public static void main(String args[]){
Lot[] lots = {new Triangle1("L1",350, 200) {},
new Triangle2("L2",100,270),
new Triangle1("L3",100, 270),
new Triangle2("L4",350,200)
};
java.util.Arrays.sort(lots);
// print out sorted results
for (Lot lot: lots) {
System.out.print(lot + " ");
System.out.println();
}
An abstract class cannot be initiated.
For you needs, first remove the abstract keyword from the class implementation.
Then, Create an constructor which get your 3 parameters, implement the 2 methods, calculateArea and getID.
Please try to start with this following code
import java.util.Comparator;
public class Triangle implements Comparator<Triangle> {
private String id;
public Triangle(String id) {
this.id = id;
}
public double calculateArea() {
int area = 0;
//calculate your area
return area;
}
public String getID() {
return id;
}
#Override
public String toString() {
return "Triangle ID: " + getID()
+ " Area: " + calculateArea();
}
#Override
public int compare(Triangle t1, Triangle t2) {
if (t1.calculateArea() > t2.calculateArea()) {
return 1;
} else if (t1.calculateArea() < t2.calculateArea()) {
return -1;
} else {
return 0;
}
}
}
Java does not allow instantiation of abstract class directly for itself.
Can we instantiate an abstract class?
Create an abstract class called Shape -> it contains an abstract method calculateArea.
Then triangle can extend this class to become an concrete implementation. Then you can instantiate objects from it.

Error; cannot find symbol; Symbol: variable super

I am working on 3 programs that contain the classes CarRental.java, LuxuryCarRental.java, and UseCarRental.java, On my LuxuryCarRental.java, I keep getting the error, Error; cannot find symbol; Symbol: variable super for the class, here is my program, I'm relatively new to Java, so please be detailed! Thanks in advance!
import java.text.DecimalFormat;
public class LuxuryCarRental extends CarRental{
private boolean chauffeur;
private double dailyChauffeurFee;
public LuxuryCarRental(String renterName, int renterZip, String sizeOfCar,int rentalDays, boolean chauffeur) {
super(renterName, renterZip, sizeOfCar, rentalDays);
this.chauffeur = chauffeur;
}
public void display(){
super.dailyRentalFee = 79.99;
this.dailyChauffeurFee = 0;
if(chauffeur){
this.dailyChauffeurFee = 200;
}
super.totalRentalFee = super.dailyRentalFee * super.getRentalDays() + this.dailyChauffeurFee * super.getRentalDays();
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Car Rental - Renter Name : " + super.getRenterName() + ", Renter Zip: " + super.getRenterZip() +
", Rental Days : " + super.getRentalDays() +
", Daily Rental Fee: " + dailyRentalFee + ", Daily Chauffer Fee: " + dailyChauffeurFee +
", Total Rental Fee: " + df.format(totalRentalFee));
}
}
And here are all the classes from all three of my programs that correspond to each other.
public class CarRental {
private String renterName;
private int renterZip;
private String sizeOfCar;
private int rentalDays;
protected double dailyRentalFee;
protected double totalRentalFee;
public class UseCarRental
public class LuxuryCarRental extends CarRental {
private boolean chauffeur;
private double dailyChauffeurFee;
public CarRental(String renterName, int renterZip, String sizeOfCar, int rentalDays)
{
renterName = renterName;
renterZip = renterZip;
sizeOfCar = sizeOfCar;
rentalDays = rentalDays;
And my altered code:
public class CarRental
{
public static void main(String[] args)
{
private String renterName;
private int renterZip;
private String sizeOfCar;
private int rentalDays;
protected double dailyRentalFee;
protected double totalRentalFee;
}
public CarRental(String renterName, int renterZip, String sizeOfCar, int rentalDays)
{
renterName = renterName;
renterZip = renterZip;
sizeOfCar = sizeOfCar;
rentalDays = rentalDays;
}
public void setDailyRentalFee(double dailyRentalFee)
{
this.dailyRentalFee = dailyRentalFee;
}
public double getDailyRentalFee()
{
return dailyRentalFee;
}
public void display(){
if(sizeOfCar.equalsIgnoreCase("economy"))
{
dailyRentalFee = 29.99;
}
else if(sizeOfCar.equalsIgnoreCase("midsize"))
{
dailyRentalFee = 38.99;
} else {
dailyRentalFee = 43.50;
}
//calculates total rental fee
this.totalRentalFee = this.dailyRentalFee * rentalDays;
DecimalFormat df = new DecimalFormat("0.00");
//displays output
System.out.println("Car Rental - Renter Name : " + renterName + ", Renter Zip: " + renterZip +
", Size of car: " + sizeOfCar + ", Rental Days : " + rentalDays +
", Daily Rental Fee: " + dailyRentalFee + ", Total Rental Fee: " + df.format(totalRentalFee));
}
public String getRenterName()
{
return renterName;
}
public int getRenterZip()
{
return renterZip;
}
public int getRentalDays()
{
return rentalDays;
}
}
super.dailyRentalFee = 79.99;
This doesn't work. The same goes for every other place you've used it.
I assume your class has a private field dailyRentalFee?
Make it protected instead. Or use public/protected getters and setters.
You're in a subclass which you should really view as an extension of the superclass. Everything that is available in the superclass is available in the subclass, provided you don't use private access but rather protected (available in current class and subclass) or public (available everywhere that has access to the current class).
Example:
class SuperClass {
protected int someValue = 5;
private int anotherValue = 10;
}
class SubClass extends SuperClass {
public void doSomething() {
someValue = 6; // I can access it because it's protected instead of private
anotherValue = 1; // I can't access it because it's private and only accessible in the SuperClass
}
}
To summarize:
Drop the super.X, super() is used to call the constructor of the superclass
Use protected or public access identifiers instead of private
First thing, super doesn't work the way you have used it.
when you extend a class, CarRental in your case, you inherite all public and protected members of that class. so to use a variable of your super class, you dont have to prefix super, you can just use the variable as if the child class holds it. so instead of
super.dailyRentalFee = 79.99;
use
dailyRentalFee = 79.99; // since dailyRentalFee is protected in class CarRental
// this will work
similarly,
super.totalRentalFee = super.dailyRentalFee * super.getRentalDays() + this.dailyChauffeurFee * super.getRentalDays();
should be written as
totalRentalFee = dailyRentalFee * getRentalDays() + this.dailyChauffeurFee * getRentalDays();
provided, the method getRentalDays is public in the CarRental class.
and about the error you mentioned in #Jeroen's answers' comments,
make sure LuxuryCarRental and CarRental are in the same package. To be simple,
make sure both files are in the same folder.
EDIT:
Your code doesn't contain a main method, that is why that error is produced. You should have a main method in your program for it to execute. That is the starting point of all java applications. so define a class with a main method inside and then create a LuxuryCarRental object and perform your computations there. for example,
class Sample {
public static void main(String[] args) { //this is how all main methods would look
LuxuryCarRental luxuryCar = new LuxuryCarRental("A",62020,"SUV",10,true);
//call the LuxuryCarRental methods as per your coding requirements
}
}
see, its simpe,
class CarRental {
//CarRental code
}
class LuxuryCarRental {
//LuxuryCarRental code
}
class Test {
public static void main(String[] args) {
LuxuryCarRental luxuryCar = new LuxuryCarRental("A",62020,"SUV",10,true);
luxuryCar.display();
}
}

How do I access variables from the main class from another class (java)?

I'm making a cookie clicker clone in java to practice my java skills and I have a small problem, I have variables that are declared in the main method that I want to access from an ActionListener class. Here is some sample code from the ActionListener class. the the int variables (ex. clicks, grandamaCost) and the JTextFields (ex. display, cpsDisplay) are all in the main method. I was wondering how I could have access to variables in the main method so that this code could work in the other class. Thanks!
#Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
button(b.getText());
}
public void button(String input) {
switch (input) {
case "Cookie":
clicks++;
display.setText("Cookies: " + clicks + "");
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy grandma":
if (clicks >= grandmaCost) {
grandmas++;
clicks = clicks - grandmaCost;
grandmaCost = (int) ((.15 * grandmaCost) + grandmaCost);
cps++;
}
display.setText("Cookies: " + clicks + "");
prices[0].setText("$" + grandmaCost);
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy monkey":
if (clicks >= monkeyCost) {
monkeys++;
clicks = clicks - monkeyCost;
monkeyCost = (int) ((.15 * monkeyCost) + monkeyCost);
cps = cps + 2;
}
display.setText("Cookies: " + clicks + "");
prices[1].setText("$" + monkeyCost);
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy Teemo":
if (clicks >= teemoCost) {
teemos++;
clicks = clicks - teemoCost;
teemoCost = (int) ((.15 * teemoCost) + teemoCost);
cps = cps + 3;
}
display.setText("Cookies: " + clicks + "");
prices[2].setText("$" + teemoCost);
cpsDisplay.setText("CPS: " + cps);
break;
}
}
}
Your variables should be fields.
Fields are declared outside of a class's methods and are usually found right below the class declaration. Fields can be accessed by all methods of a class.
They can also be accessed from other classes (unless they are private) using the dot operator.
If a field is marked with static, its class name is used to reference it.
If a field is not static, an object of its class is used to reference it.
Example
public class Man {
public String name; //this is a field
public static String gender = "Male"; //this is a static field
public Man(String newName) {
name = newName; //assigns the value of a field from within a method
}
}
and another class...
public class Main {
public static void main(String[] args) {
Man bob = new Man("Bob");
System.out.println(bob.name); //referenced from object, prints Bob
System.out.println(Man.gender); //referenced from class name, prints Male
}
}
And to have more control over the access of your fields, you can use getters and setters. Take a read!
public class ActionClass {
{
private static int clicks;
#Override
public void actionPerformed(ActionEvent e) {
clicks++;
}
public static void setClicks(int c){
clicks = c;
}
public static int getClicks(){
return clicks;
}
}
public class AnyClass {
{
// now you have access to your clicks count .
int clicks = ActionClass.getClicks();
// set value of clicks
ActionClass.setClicks(0);
}
Here, I will give you an example for exactly what you need. In this code you simply just need to set anything you would like to add to actionPerformed as static.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class testJava implements ActionListener {
protected static JButton b; // since this is static you can
// now access it in other classes
public static void main(String[] args) {
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == b) {
// do stuff here
}
}
}
You would have to make the variables public class variables instead of method variables, thereby increasing the scope and visiblity of the variables. Like so:
public class ActionClass {
{
public string MyPublicVariable = "woot";
#Override
public void actionPerformed(ActionEvent e) {
...
}
}
A more popular/recommended way to do this is to use a getter/setter instead of making the variable explicitly public. You would access a private variable through public methods like so:
public class ActionClass {
{
#Override
public void actionPerformed(ActionEvent e) {
private string MyPublicVariable = "woot";
public void setMyString(string newString){
MyPublicVariable = newString;
}
public string getMyString(){
return MyPublicVariable;
}
}
}
This way, you have more control over what your variables are set to.
Using fields and their accessor methods. An example here.
You can pass main class instance reference to another class instance, or register callback.
For the first way
Class MainClass {
private int mValue;
public void init() {
AnotherClass cla = new AnotherClass(this);
}
public void setValue(int value) {mValue = value;}
public int getValue(){return mValue;}
}
Class AnotherClass {
private MainClass mMain;
public AnotherClass(MainClass ref) {
mMain = ref;
}
public void controlValue() {
if (mMain != null) {
mMain.setValue(1);
mMain.getValue();
}
}
}
For the second way
1. declare an interface
2. implement this interface in main class
3. register this implementation to another class.
4. get and set value in another class.
public interface ClassListener {
public void setValue(int value);
public int getValue();
}
public class MainClass implements ClassListener{
private int mValue;
public void registerListener() {
AnotherClass cla = new AnotherClass();
cla.registerListener(this);
}
#Override
public void setValue(int value) {
// TODO Auto-generated method stub
mValue = value;
}
#Override
public int getValue() {
// TODO Auto-generated method stub
return mValue;
}
}
public class AnotherClass{
private ClassListener mListener;
public void registerListener(ClassListener listener) {
mListener = listener;
}
public void controlValue() {
if (mListener != null) {
int value = mListener.getValue();
mListener.setValue(++value);
}
}
}

Abstract class error in java

I'm trying to figure out why i keep getting the error that my AM class does not override abstract method. In my teachers UML diagram it only shows that i need the equals (Object o) method in my parent radio class. Also i'm not declaring it as abstract in my abstract class.
public abstract class Radio implements Comparable
{
double currentStation;
RadioSelectionBar radioSelectionBar;
public Radio()
{
this.currentStation = getMin_Station();
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{
}
public void down()
{
}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
this.currentStation = freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
public boolean equals (Object o)
{
if (o == null)
return false;
if (! (o instanceof Radio))
return false;
Radio other = (Radio) o;
return this.currentStation == other.currentStation;
}
public static void main(String[] args)
{
Radio amRadio = new AMRadio();
System.out.println(amRadio);
Radio fmRadio = new FMRadio();
System.out.println(fmRadio);
Radio xmRadio = new XMRadio();
System.out.println(xmRadio);
}
}
public class AMRadio extends Radio
{
private static final double Max_Station = 1605;
private static final double Min_Station = 535;
private static final double Increment = 10;
public AMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("AM " + this.currentStation);
return message;
}
}
You have to implement the compareTo() method, given that Radio implements the Comparable interface and a concrete implementation for this method wasn't provided in the Radio class, so you have two choices:
Implement compareTo() in all of Radio's subclasses
Or implement compareTo() in Radio
Something like this, in AMRadio:
public int compareTo(AMRadio o) {
// return the appropriate value, read the linked documentation
}
Or like this, in Radio:
public int compareTo(Radio o) {
// return the appropriate value, read the linked documentation
}

How to write a method that returns an instance of an abstract class?

I am a beginner in Java and i trying to understand the abstract classes.
Below is the code that I've written; the question is: how do i write a method that will return an instance of that class.
public abstract class VehicleEngine
{
protected String name;
protected double fabricationCons;
protected double consum;
protected int mileage;
public VehicleEngine(String n, double fC)
{
name = n;
fabricationCons = fC;
mileage = 0;
consum = 0;
}
private void setFabricationCons(double fC)
{
fabricationCons = fC;
}
public abstract double currentConsum();
public String toString()
{
return name + " : " + fabricationCons + " : " + currentConsum();
}
public void addMileage(int km)
{
mileage += km;
}
public double getFabricationConsum()
{
return fabricationCons;
}
public String getName()
{
return name;
}
public int getMileage()
{
return mileage;
}
//public VehicleEngine get(String name){
//if(getName().equals(name)){
//return VehicleEngine;
//}
//return null;
//}
}
public class BenzinVehicle extends VehicleEngine
{
public BenzinVehicle(String n, double fC)
{
super(n, fC);
}
#Override
public double currentConsum()
{
if (getMileage() >= 75000) {
consum = getFabricationConsum() + 0.4;
} else {
consum = getFabricationConsum();
}
return consum;
}
}
public class DieselVehicle extends VehicleEngine
{
public DieselVehicle(String n, double fC)
{
super(n, fC);
}
#Override
public double currentConsum()
{
int cons = 0;
if (getMileage() < 5000) {
consum = getFabricationConsum();
} else {
consum = getFabricationConsum() + (getFabricationConsum() * (0.01 * (getMileage() / 5000)));
}
return consum;
}
}
This is the main.
public class Subject2
{
public static void main(String[] args)
{
VehicleEngine c1 = new BenzinVehicle("Ford Focus 1.9", 5.0);
DieselVehicle c2 = new DieselVehicle("Toyota Yaris 1.4D", 4.0);
BenzinVehicle c3 = new BenzinVehicle("Citroen C3 1.6",5.2);
c1.addMileage(30000);
c1.addMileage(55700);
c2.addMileage(49500);
c3.addMileage(35400);
System.out.println(c1);
System.out.println(c2);
System.out.println(VehicleEngine.get("Citroen C3 1.6")); //this is the line with problems
System.out.println(VehicleEngine.get("Ford Focus "));
}
}
And the output should be:
Ford Focus 1.9 : 5.0 : 5.4
Toyota Yaris 1.4D : 4.0 : 4.36
Citroen C3 1.6 : 5.2 : 5.2
null
You can not return an instance of an abstract class, by definition. What you can do, is return an instance of one of the concrete (non-abstract) subclasses that extend it. For example, inside the VehicleEngine you can create a factory that returns instances given the type of the instance and the expected parameters, but those instances will necessarily have to be concrete subclasses of VehicleEngine
Have a look at the Factory Method pattern. Your concrete classes will implement an abstract method that returns a class instance.
Abstract classes do not keep a list of their instances. Actually no Java class does that. If you really want to do that, you could add a static map to VehicleEngine like this:
private static Map<String, VehicleEngine> instanceMap = new HashMap<String, VehicleEngine>();
and change your get method to a static one like this:
public static VehicleEngine get(String name) {
return instanceMap.get(name);
}
and add this line to the end of the constructor of VehicleEngine:
VehicleEngine.instanceMap.put(n, this);
this way every new instance created puts itself into the static map. However this actually is not a good way to implement such a functionality. You could try to use a factory to create instances, or you could consider converting this class into an enum if you will have a limited predefined number of instances.

Categories