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

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.

Related

java print arraylist of interface

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;
}

Java: How to I get values inside ArrayList when there's parent/child involved?

So I have an ArrayList of objects. Inside those objects are various attributes and their values.
The code is pretty simple. GBox and GCircle are childs of GHP. The ArrayList is in World.
What I want to do is print the HP and volume of the box and the HP and diameter of the circle. I understand I could override toString() but I actually want to get the values. What's the correct syntax to do so?
//Main.java
public class Main {
public static void main(String[] args) {
Ini i = new Ini();
}
}
//Ini.java
public class Ini {
private static World w;
public Ini() {
w = new World;
w.makeGBox();
w.makeGCircle();
System.out.println("Box: HP: " +
w.getList().get(0).getHP() +
"Volume: " +
w.getList().get(0).GBox.getVolume());
//compile error no variable GBox in GHP
System.out.println("Circle: HP: " +
w.getList().get(1).getHP() +
"Radius: " +
w.getList().get(1).GCircle.getRadius());
//compile error no variable GCircle in GHP
}
}
//World.java
import java.util.ArrayList;
public class World {
private ArrayList<GHP> list = new ArrayList<>();
public void makeGBox() {
list.add(new GBox());
}
public void makeGCircle() {
list.add(new GCircle());
}
public ArrayList<GHP> getList() {
return list;
}
}
//GHP.java
public class GHP {
private int HP;
public GHP() {
setHP(5);
}
public int getHP() {
return HP;
}
public void setHP(int HP) {
this.HP = HP;
}
}
//GBox.java
public class GBox extends GHP{
private int volume;
public GBox() {
setVolume(10);
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
//GCircle.java
public class GCircle extends GHP{
private int radius;
public GCircle {
setRadius(7);
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
Apart from the many compilation problems, you need these changes to achieve what you want.
for (GHP ghp : w.getList()) { // Avoid using get(index) without a forloop, as such
if (ghp instanceof GBox) { // Using the instanceof operator, you can differentiate the 2 class types
System.out.println("Box: HP: " + ghp.getHP() + "Volume: "
+ ((GBox) ghp).getVolume()); // Cast it to GBox to be able to call getVolume
}
if (ghp instanceof GCircle) {
System.out.println("Circle: HP: " + ghp.getHP() + "Radius: "
+ ((GCircle) ghp).getRadius());// Cast it to GCircle to be able to call getRadius
}
}
You would need to cast the generic GHP reference to the specific type like:
((GCircle) ghp).getRadius()
You might also want to have a look on instanceof operator.
The idea being:
for output you override the toString() method because you don't need any class specific information, just print out object details
for class-specific operations you downcast to he specific type
When you read the list values, the only thing the compiler knows, is that the list contains GHP instances.
First check the type and then cast it to the subclass.
GHP ghp = w.getList().get(0);
if(ghp instanceof GBox) {
GBox gbox = (GBox) ghp;
// Here you can access the method getVolume()
/* ... */ gbox.getVolume();
}
A cleaner, more OOP alternative to adding methods to the base class and/or instanceof checks is to use the Visitor pattern that allows you to separate your object structure from any algorithms that operate on them. The algorithm in this case is simply a "display" algorithm.
That said, for most simple cases (like this one) adding methods to the base class and overriding or using instanceof is fine.
List<Shape> shapes = new ArrayList<Shape>();
....
...
for (Shape shape : shapes) {
System.out.println(shape.getHp());
if(shape instanceof Circle){
System.out.println(((Circle) shape).getValuem());
}else if(shape instanceof Box){
System.out.println(((Box) shape).getHieght());
}
try this way..

Beginning Java Polymorphism Subclass Superclass

I am trying to practice with Polymorphism and using classes. I wrote a superclass called Card. I then wrote 3 subclasses called: IDCard, CallingCard, and DriverLicense. I then wrote another class called Billfold which is supposed to contain slots for two of the cards.
I am supposed to write a BillfoldTester program which adds two objects of different subclasses to a Billfold object.
In BillfoldTester, a DriverLicense object and a CallingCard object are instantiated and added to a Billfold, which refers to these objects with Card references.
I don't really understand how to do this. I created two Card objects but I am trying to add it to my Billfold and it wont work. I tried Billfold a = new Card (x); but it's not right... Any help is much appreciated.
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
//Having trouble trying to put the objects into my Billfold and print it.
}
}
public class Billfold extends Card
{
private String card1;
private String card2;
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
}
public class Card
{
private String name;
public Card()
//This is my superclass
{
name = "";
}
public Card(String n)
{
name = n;
}
public String getName()
{
return name;
}
public boolean isExpired()
{
return false;
}
public String format()
{
return "Card holder: " + name;
}
}
public class IDCard extends Card
{
//This is one of my subclasses
private int IDNumber;
public IDCard (String n, int id)
{
super(n);
this.IDNumber=id;
}
public String format()
{
return super.format() + IDNumber;
}
}
The polymorphism example. Not sure if the functionally is exactly what you need, but you can see the whole idea (I hope). See the showAllFormat() method of Billfold class.
The whole point is inside different format() methods of the DriverLicense and IDCard. Depending on the 'real' (or initially assigned) object the different method will be called even if you just only refer to 'Card' class.
NOTE:
You didn't provide your DriverLicense implementation, and my is just from head. I have a bit different constructor to show this sub-classes may be totally different.
import java.util.ArrayList;
import java.util.List;
class Billfold {
List<Card> list = new ArrayList<Card>(10);
void addCard(Card card) // Q: Not sure if this should be String
// A: You would like to add a Card
{
list.add(card);
}
void showAllFormat() {
// go polymorphism !...
// when you call this general 'format()' you see the subclasses
// 'format()' is executed, not from 'Card' class
for(Card x: list) {
System.out.println(x.format());
}
}
}
class Card {
private String name; /* owner */
public Card() //This is my superclass
{
name = "";
}
public Card(String n) {
name = n;
}
public String getName() {
return name;
}
public boolean isExpired() {
return false;
}
public String format() {
return "Card holder: " + name;
}
}
class IDCard extends Card {
//This is one of my subclasses
private int IDNumber;
public IDCard(String n, int id) {
super(n);
this.IDNumber = id;
}
public String format() {
return "(ID)" + super.format() + " " + IDNumber;
}
}
class DriverLicense extends Card {
private String type;
public DriverLicense(String n, String type) {
super(n);
this.type = type;
}
public String format() {
return "(DL)" + super.format() + " TYPE: " + type;
}
}
public class BillfoldTester {
public static void main(String[] args) {
Card x = new IDCard("Julie", 1995);
Card j = new DriverLicense("Jess", "AB");
Billfold bf = new Billfold();
bf.addCard(x);
bf.addCard(j);
bf.showAllFormat();
}
}
This is wrong. A Billfold is not a Card; it HAS Cards.
public class Billfold
{
List<Card> cards = new ArrayList<Card>();
void addCard(Card card) {
if (card != null) {
this.cards.add(card);
}
}
}
Prefer composition over inheritance.
You should have Billfold class have two Card objects, not two Strings:
public class Billfold
{
Card card1;
Card card2;
void addCard(Card card) {
if (card != null) {
if (card1 != null) {
this.card1 = card;
} else {
this.card2 = card;
}
}
}
Ok, you're largely on the right track, just a couple of things:
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
You're right, this should be:
void addCard(Card card)
{
card1=card;
}
then to add them:
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
Billfold bf = new Billfold();
Billfold.addCard(x);
Billfold.addCard(j);
}
}
Then add a method to Billfold to print the cards in it.
Edit: Oh yeah, and duffymo is totally right, you don't need to extends Card on Billfold

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.

implementing and interfaces

I tried looking up tutorials and videos and I understand what implementing does, although I'm a bit confused as to how one would implement a class from the Java Library. In my homework, I'm suppose to utilize the class, DataSet and make it so it accepts Comparable objects. The program is suppose to record the Min and Max values depending on the objects, in this case, I'm suppose to use strings. I wasn't sure if I needed any classes to implement the Comparable interface, so I made two classes just in case I was suppose to do so. My real question is how do I actually incorperate a String variable in the tester class to actually read and compare the object to another? thanks in advance.
public class Word implements Comparable
{
private String str;
public Word()
{
str = null;
}
public Word(String s)
{
str = s;
}
public int compareTo(Object other)
{
String n = (String) other;
return str.compareTo(n);
}
}
I wasn't sure which of the two classes would be suitable for implementing Although i think the String class below would not work at all b/c It's already a standard class so I wasn't too sure about using it
public class String implements Comparable
{
public String s;
public String()
{
s = null;
}
public String(String str)
{
s = str;
}
public int compareTo(Object other)
{
String n = (String) other;
return s.compareTo(n);
}
}
public interface Comparable
{
public int compareTo(Object other);
}
public class DataSet
{
private Object maximum;
private Object least;
private Comparable compare;
private int count;
public DataSet(Comparable s)
{
compare = s;
}
public void add(Object x)
{
if(count == 0)
least = x;
if(count == 0 || compare.compareTo(x) >=0)
maximum = x;
else if(compare.compareTo(x) <0)
least = x;
count++;
}
public Object getMaximum()
{
return maximum;
}
public Object getLeast()
{
return least;
}
}
public class DataSetTester
{
public static void main(String[] args)
{
Comparable n = new Word("sand");
DataSet data = new DataSet(n);
data.add(new Word(man));
System.out.println("Maximum Word: " + data.getMaximum());
System.out.println("Least Word: " + data.getLeast());
}
}
An interface is a contract that showes that your class contain all methodes that are implemented in the interface. In this case the CompareTo(object other). The String class already implements the comparable interface so you don't need youre own class. I think your data set class should look something like this :
public class DataSet<T implements Comparable>
{
private T maximum;
private T least;
private T count;
public void add(T x)
{
if(count == 0){
least = x;
maximum = x;
}
else if(least.compareTo(x) > 0)
least = x;
else if(maximum.compareTo(x) < 0)
maximum = x;
count++;
}
public T getMaximum()
{
return maximum;
}
public T getLeast()
{
return least;
}
}
T is a generic type and in your case it should be String, Here is how you create a new Data set:
DataSet<String> ds = new DataSet<String>;

Categories