set interface problem and objects
sorry for bad Subject of topic but i couldnt find out what to write proper. (please correct topic if it gives missunderstood).
So my problem is: I have interface Shape and two classes implements after this Circle and Square. I need to write class which will collect Circle and Square. It must be one of methods of collecting which will not add any duplicate objects. I've chosen "set" after reading in documentation of java. But i am not sure if it was good idea. (i can use one of the four methods: map. set. list. or queque).
After all I created another class named ShapeSet and method
public void ShapeSet(Shape Set)
It looks like this:
public class ShapeSet {
public ShapeSet() {}
Set <Shape> setting; //is it wrong?
public void addShape(Shape shape) {
setting.add(shape);
}
...
}
After that thinking that i am doing right i created in main class, constructor defining square and circle. I created also ShapeSet ss
.
public static void main(String[] args) {
// TODO code application logic here
ShapeSet ss = new shapes.ShapeSet();
Shape c = new Circle(3);
Shape s = new Square(4);
s开发者_如何学Cs.addShape(c);
ss.addShape(s);
ss.iterator();
}
But while running program i got error on line ss.addShape(x), netbeans complains that he found null exception. Why? ;( I think types inputed to method shapeset was wrong and maybe bad position of declaring set setting. But how to fix that? I am total novice in java. I appreciate for a help. Thanks in advance.
The answer about the NullPointerException is probably because in your ShapeSet class, you haven't allocated the member field 'setting' as in
Set <Shape> setting = new HashSet<Shape>();
The question I have however, is why have a ShapeSet class at all? It seems you only need to have Set as a field in the class that has the main method.
You forgot to initialize your field setting
public class ShapeSet {
public ShapeSet() {}
Set <Shape> setting = new HashSet<Shape>();
public void addShape(Shape shape) {
setting.add(shape);
}
...
}
I agree with @MeBigFatGuy - you don't need your ShapeSet
class. You can code your main like this:
public static void main(String[] args) {
Set<Shape> ss = new HashSet<Shape>(); // or some other Set concrete class
Shape c = new Circle(3);
Shape s = new Square(4);
ss.add(c);
ss.add(s);
ss.iterator(); // actually, you'd want to do something with the iterator
}
精彩评论