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);
ss.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
}
Related
So, I am a learning programmer and I started to learn Java 2 months ago as a course at my university. I really like to program in my spare time and I'm currently trying to make a game. There is one problem at the moment which I just can't solve.
I have a class called Move, and I declare in my class called Start:
Move move1 = new Move();
Now when I'm back in my Move class, I would like to access this move1 but it doesn't let me. It says:classname cannot be resolved.
To clarify:
public class Move {
private String s = null;
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
public void setList() {
System.out.println(move1.getName() + move2.getName()); // This won't work
}
}
And the start class:
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
}
}
It would be awesome if someone could help me out!
-edit
OK! I got a few reactions but I didn't really get the answer I need. I know now i can use this instead of the object name but what if I want to use a second object? I changed code the above.
The problem you have is that the names move1 and move2 are out of scope in the setList method. They're defined in Start.main as local variables, so they are only visible there.
There are a innumerable ways you can solve this. The most straight-forward way is to move the setList method to Start. Because you're calling it from main, which is a static method, setList will also have to be static.
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
setList(move1, move2);
}
public static void setList(Move move1, Move move2) {
System.out.println(move1.getName() + move2.getName());
}
}
If you think setList should be in the Move class, you'll need to pass the second move as a parameter.
public class Move {
...
public void setList(Move other) {
System.out.println(this.getName() + other.getName());
}
}
You don't need to say move1.getName(). You can say this.getName() instead. The keyword this refers to whatever object is calling the method - in this case, move1.
This is because the object move1 only exists in the scope of the main method in Start. Therefore, "move1" is meaningless anywhere other than main.
In reality, the keyword this can be omitted; you could just say getName() without putting anything in front of it.
move1 is the object of Move class define in the Start class so you cant access it.You can simply access the method of Move class with below line.
System.out.println(getName()); // THis will work
The correct way to access current move object (move1) is using this key word. You could say System.out.println(this.getName()); in Move class.
Maybe you didn't add import of class Move? It necessary when you access an object from a different package.
I've got three classes:
One class which handles my main game operations. Its name is 'PlatformerGame'.
Note: Removed all game-related stuff.
public class PlatformerGame {
public PlatformerGame()
{
}
}
Then, I've got a class called 'PlatformerSingleton' which is meant to provide exactly one instance of the PlatformerGame.
public class PlatformerSingleton {
private static PlatformerGame game;
protected PlatformerSingleton()
{}
public static PlatformerGame getGame()
{
if (game == null)
game = new PlatformerGame();
return game;
}
}
And lastly, I've got the entry point of my application which is supposed to do nothing but get the instance of PlatformerGame and call its 'start' method.
public class Entry {
public static void main(String[] args) {
new PlatformerSingleton.getGame().start();
}
}
However, this is where the error happens:
What does this error mean and how can I prevent it? Also, are there any better approaches to implement this?
Note: I require access to the singleton instance from multiple classes, therefore I need this singleton class.
Don't add new in the line new PlatformerSingleton.getGame().start();
just change your line to:
PlatformerSingleton.getGame().start();
you are not creating new object here, you are just calling the static method of PlatformerSingleton class in which the object of the class is created using Singleton Design Pattern
Remove the new in that call:
new PlatformerSingleton.getGame().start();
Currently, it looks like you're trying to instantiate a class called PlatformerSingleton.getGame (a static nested class called getGame inside PlatformerSingleton).
You're looking for the static method inside PlatformerSingleton. Since it's static, you don't want to instantiate using new at all.
The compiler sees that the syntax is correct, but it doesn't find such class and thus throws an error. These kinds of errors are a bit tougher to correctly debug (as the actual error is syntactical), so you need to look a bit farther to fix it.
Just remove the newkeyword (you don't need new because you're creating PlatformerGameinstance inside of the getGame method):
public static void main(String[] args) {
PlatformerSingleton.getGame().start();
}
Since getGame() is a static method, you do not need to use the new keyword to call the method.
public static void main(String[] args) {
PlatformerSingleton.getGame().start(); // new keyword is not required
}
If getGame() was not static, only then it would have required an instance of PlatformerSingleton class for it to be called and that would have looked like
public static void main(String[] args) {
new PlatformerSingleton().getGame().start(); // if getGame() was a non-static method
}
I have a question regarding to using method in main class, here is my code for a Race class:
import java.util.ArrayList;
public class Race {
private ArrayList<Car>cars;
public Race(){
cars = new ArrayList<Car>();
}
public void addCars(Car car){
cars.add(car);
}
}
The above is what I have done to make an arraylist for the cars that I am ready to put in by using a main method in another class:
public class Test {
public static void main(String[] args) {
Car toyota = new Car("Toyota",1.0,1.0,2.0,2.0);
cars.addCars(toyota);
}
}
However, it has error in the last line, it shows "cars cannot be resolved",I am not sure how should I fix it, maybe writing a getter method in the Race class?
Create an instance of race and call addCars
Race race = new Race();
race.addCars(toyota);
cars does not exist in that context, you might want to stick to the convention on having lowercase variable names, as well.
Change your Test class to something similar to this:
public class Test {
public static void main(String[] args) {
Race race = new Race();
Car toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
race.addCars(toyota);
}
}
You want to add cars to the race, not cars (which does not exist).
To add cars to a race, you first need to make one.
By adding cars to the race, it will internally add it to the cars list. (Because you made it so)
You problem is basically that you are trying to use a variable that is outside the scope. (Somewhere else, basically)
Since I don't know your exact problem, I can't really help you further, but you might want to save the race in a field rather than a local variable, it all depends on what you want to do.
I have an application that is pretty much now complete, however I have several methods within the main class so it looks very untidly/large.
I want to separate these methods out into separate classes but despite me trying this I continually get null pointer errors.
Even when creating just a string within another class and trying to obtain that within another I am getting null results.
I have done a search on here but nothing really answers my questions, I would appreciate some help.
Edit: here is some example code:
public class Test2 extends mainClass{
public ArrayList<ExtendedOverlayItem> somethingz = new ArrayList<ExtendedOverlayItem>();
public void addSomething() {
ExtendedOverlayItem poi = new ExtendedOverlayItem(
"description", "description", new GeoPoint(88.123058,
-10.987654), null);
poi.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
poi.setDescription("test");
somethingz.add(poi);
ItemizedOverlayWithBubble<ExtendedOverlayItem> node = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(
this, somethingz, map);
map.getOverlays().add(node);
}
public ArrayList<ExtendedOverlayItem> getSomethingz() {
return somethingz;
}
public Test2(ArrayList<ExtendedOverlayItem> somesthingz) {
super();
this.somesthingz =somesthingz;
}
public void setSomethingz(ArrayList<ExtendedOverlayItem> somesthingz) {
this.somesthingz = somesthingz;
}
}
Then in my main class I have simply added
Test2 test;
Then called the method with: test.addSomething();
I am most likely missing something trivial, but I have even just tried this with a string in the test2 class then attempting to print it out from the main class but it results in null pointers.
Thanks.
it sounds like you are maybe trying to do this:
Test2 test;
test.addSomething();
If so, then you need to instantiate the object like so:
ArrayList<ExtendedOverlayItem> itemList = new ArrayList<ExtendedOverlayItem>();
Test2 test = new Test2(itemList);
test.addSomething();
Take a look at some of the various introductory Java tutorials out there to get familiar with the language.
Lets suppose I have the following two classes
public class alpha {
public alpha(){
//some logic
}
public void alphaMethod1(){
//some logic
}
}
public class beta extends alpha {
public beta(){
//some logic
}
public void alphaMethod1(){
//some logic
}
}
public class Test extends beta
{
public static void main(String[] args)
{
beta obj = new beta();
obj.alphaMethod1();// Here I want to call the method from class alpha.
}
}
If I initiate a new object of type beta, how can I execute the alphamethod1 logic found in class alpha rather than beta? Can I just use super().alphaMethod1() <- I wonder if this is possible.
Autotype in Eclipse IDE is giving me the option to select alphamethod1 either from class alpha or class beta.
You can do:
super.alphaMethod1();
Note, that super is a reference to the parent class, but super() is its constructor.
Simply use super.alphaMethod1();
See super keyword in java
You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:
solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}
or from any other method of Beta like:
class Beta extends Alpha
{
public void foo()
{
super.alphaMethod1();
}
}
class Test extends Beta
{
public static void main(String[] args)
{
Beta beta = new Beta();
beta.foo();
}
}
solution 2: create alpha's object and call alpha's alphaMethod1()
class Test extends Beta
{
public static void main(String[] args)
{
Alpha alpha = new Alpha();
alpha.alphaMethod1();
}
}
It is possible to use super to call the method from mother class, but this would mean you probably have a design problem.
Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().
If it depends on the situation, you can put some code logic like :
public void alphaMethod1(){
if (something) {
super.alphaMethod1();
return;
}
// Rest of the code for other situations
}
Like this it will only call A's method when needed and will remain invisible for the class user.
Whenever you create child class object then that object has all the features of parent class.
Here Super() is the facilty for accession parent.
If you write super() at that time parents's default constructor is called.
same if you write super.
this keyword refers the current object same as super key word facilty for accessing parents.
Solution is at the end of this answer, but before you read it you should also read what is before it.
What you are trying to do would break security by allowing skipping possible validation mechanisms added in overridden methods.
For now lets imagine we can invoke version of method from superclass via syntax like
referenceVariable.super.methodName(arguments)
If we have classes like
class ItemBox{ //can sore all kind of Items
public void put(Item item){
//(1) code responsible for organizing items in box
}
//.. rest of code, like container for Items, etc.
}
class RedItemsBox extends ItemBox {//to store only RED items
#Override
public void put(Item item){ //store only RED items
if (item.getColor()==Color.RED){
//(2) code responsible for organizing items in box
}
}
}
As you see RedItemsBox should only store RED items.
Regardless which of the below we use
ItemBox box = new RedItemsBox();
RedItemsBox box = new RedItemsBox();
calling
box.put(new BlueItem());
will invoke put method from RedItemsBox (because of polymorphism). So it will correctly prevent BlueItem object from being placed in RedItemBox.
But what would happen if we could use syntax like box.super.put(new BlueItem())?
Here (assuming it would be legal) we would execute version of put method from ItemBox class.
BUT that version doesn't have step responsible for validating Item color. This means that we could put any Item into a RedItemBox.
Existence of such syntax would mean that validation steps added in subclasses could be ignored at any time, making them pointless.
There IS a case where executing code of "original" method would make sense.
And that palce is inside overriding method.
Notice that comments //(1) .. and //(2).. from put method of ItemBox and RedItemBox are quite similar. Actually they represent same action...
So it makes sense to reuse code from "original" method inside overriding method.
And that is possible via super.methodName(arguments) call (like from inside put of RedItemBox):
#Override
public void put(Item item){ //store only RED items
if (item.getColor()==Color.RED){
super.put(item); // <<<--- invoking code of `put` method
// from ItemBox (supertype)
}
}
beta obj = new beta();
Since you have created beta object , you cant refer directly to alphamethod1 of alpha object.
It can be modified as
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}