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.
Related
Why my access to non static string variable doesn't work. Try to do it and my IDE found it already but when I run it show "Cannot find symbol"
Please help me, Thank You.
public class Main
{
public static void main(String[] args)
{
testWrong obj = new testWrong();
System.out.println(obj.public_non_static()); //Doesn't Work
}
}
public class testWrong
{
public String public_non_static = "It is Public non Static";
public void in_non_static_method()
{
testWrong obj1 = new testWrong();
obj1.public_non_static(); //Doesn't Work
}
public static void in_static_method()
{
testWrong obj2 = new testWrong();
obj2.public_non_static(); //Doesn't Work also
}
}
You have a variable named public_non_static but you try to access a method with that name which does not work in Java.
on the other hand you should not get used to access variables in other classes directly since it violates the most important OO principle information hiding/encapsulation.
The same is true for getter/setter methods which should only be used on stupid data transfer objects (DTOs) or Value Objects which have no (business) logic.
You are accessing like a method :public_non_static();
Use this instead : obj2.public_non_static;
And since you are like very new to OOP, it's the best practice to not to use public keyword and you should make them private and make getters and setters for them.
I have the following code class Agent.java :
public class Agent {
Helper helper ;
private class SpecificBehaviour extends Behaviour{
private Apple a;
public SpecificBehaviour(Apple a){
setApple(a);
}
public void setApple(Apple a){
this.a=a;
}
public Apple getApple(){
return a;
}
}
public void someMethod(){
helper = new Helper(this);
}
}
In the Helper.java ( another class within the same package) I would like to access the getApple() method. did some search and found this link
I am wondering if there is a better/ easier way of doing this ?
There are at least two issues here:
Helper doesn't know of the existence of SpecificBehaviour, because it's a private class. It could potentially know about the Behaviour class, which you haven't given any details of. If getApple() is declared in Behaviour, and if Behaviour is visible to Helper, then the visibility part needn't be a problem.
Helper will need a reference to an instance of SpecificBehaviour, which means you'll need to instantiate SpecificBehaviour. For that, you'll also need an instance of Agent, because SpecificBehaviour is an inner class. It's not clear whether you have such an instance.
Basically I think the presence of a private inner class is adding confusion here. If you're reasonably new to Java, I'd strongly recommend sticking to top-level classes for the moment. They have a few subtleties around them, and it's best to try to learn one thing at a time.
If this doesn't help, please give more context - your question is quite vague at the moment. Where do you want to use getApple within Helper? Should part of the state of Helper be a reference to an instance of SpecificBehaviour, or should it be a method parameter? Have you created an instance of Agent? What does Behaviour look like? You may find that in the course of answering these questions one at a time, you're better able to figure out the problem for yourself.
- Use Composition principle to get the access to the getApple() method.
Eg:
public class Agent {
Apple a = new Apple(); // Agent class has a reference of type Apple.
.....
.....
}
- Second way would be to make the getApple() method static in Apple class, and then access it from Agent class using the Class name with . (dot) operator.
Eg:
public class Agent {
public void go(){
Apple.getApple();
}
.....
.....
}
You need to ask the Agent object you are passing to the Helper for the instance of the private class SpecificBehaviour. This is the way it works. Encapsulation remember.
Jon Skeet stated that and I completely agree on it:
Helper will need a reference to an instance of SpecificBehaviour,
which means you'll need to instantiate SpecificBehaviour. For that,
you'll also need an instance of Agent, because SpecificBehaviour is an
inner class. It's not clear whether you have such an instance.
Actually, you can understand how weird your try is by testing the sample code below:
Agent.java
public class Agent
{
private class SpecificBehaviour
{
public String toString()
{
return "specific behaviour";
}
}
public Class getInner()
{
return SpecificBehaviour.class;
}
}
Helper.java
public class Helper
{
public static void main(String[] args)
{
try
{
Agent agent = new Agent();
System.out.println(agent.getInner().newInstance().toString());
}
catch (InstantiationException e) { e.printStackTrace(); }
catch (IllegalAccessException e) { e.printStackTrace(); }
}
}
The code above just compiles fine. And let's see what the output is:
java.lang.InstantiationException: Agent$SpecificBehaviour
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at Helper.main(Helper.java:5)
[please note this may require AS3 + Java knowledge]
Background Information:
I'm trying to build a game using Java + Pulpcore, but I'm fairly new to the scene. The game I'm building could possibly be more performance intensive than I thought, and I know Java would solve my problems with this, but there are a couple questions I have dealing with strict-types, etc.
Here is my code in AS3:
Main.as3
import org.tbmb.champions.Container;
import org.tbmb.zombies.ZContainer;
public class Main extends MovieClip {
// ******* temporary properties ******* /
private var blunder:Container = null;
// ******* ******* /
public function Main() {
init(); // initialize objects
}
public function init():void {
blunder = new Container(Blunder as Class);
} // end of class
}
Container.as3
package org.tbmb.champions {
import flash.display.MovieClip;
public class Container extends MovieClip {
public function Container(champ:*) {
} // end of constructor
} // end of class
} // end of package
Blunder.as3
package org.tbmb.champions.blunder {
import flash.display.MovieClip;
public class Blunder extends MovieClip {
public function Blunder() {
} // end of constructor
} // end of class
} // end of constructor
1.) How would I rewrite in Java?
blunder = new Container(Blunder as Class);
2.) How would I be able to accept any Classes in Java for the above line within my Container class?
public function Container(champ:*) {
I need to do this because I'm sending different champion classes (depending on what the user picks) to a containing class that will hold all their other classes (health, etc). I need my Container class to accept any Class rather than just one; what type would I use?
Here is what I have in Java so far:
ZomboPulp.java (Main Class)
import pulpcore.scene.Scene2D;
import org.tnpfk.champions.Container;
import org.tnpfk.champions.blunder.Blunder;
import pulpcore.sprite.FilledSprite;
import pulpcore.image.Colors;
public class ZomboPulp extends Scene2D {
FilledSprite background = new FilledSprite(Colors.WHITE);
Container container = null; // Container that contain's blunder,
// and all his objects (health, mana, etc)
public void load() {
this.initScreen(); // initialize main screen.
this.initObjects(); // initialize our objects.
} // end of load();
public void initScreen() {
add(background);
} // end of initScreen();
public void initObjects() {
container = new Container(Blunder as Class); // ERROR HERE
} // end of initObjects();
}
Container.java
package org.tnpfk.champions;
public class Container {
public Container(Object champ) {
} // end of constructor
} // end of class
Sorry for the lengthy post, and thanks for any help. By the way, I did check StackOverflow; and Google, but I was unable to find anything about this.
Thanks,
jvmpulp
Alrighty! I have no experience with PulpCore, but I do know both AS3 and Java, so I think I can answer your question. First off, I guess I don't 100% understand what you need to do with the champ object in the Container class, and I really don't understand why you were doing Blunder as Class instead of just passing an instance of Blunder. Either way, here's what I'd recommend with what you have as of now:
public void initObjects() {
container = new Container(Blunder.class);
}
As you can see, you can get a Class instance just by getting the class property of any class. Now, you have the right idea with using Object as the type for the Container constructor for any type. However, using Object is bad practice (use method overloading/more specific types instead), and it's not even required here. Getting the class property will always be of type Class, even though they represent different classes. So, rewrite the constructor as this:
public Container(Class champ) {
}
Then, do whatever you need to do with the class.
Now, that's basically a direct port, but it seems some of the things you're doing are bad practice. The whole system of passing a Class object seems irrelevant and unnecessary; why not just pass an instance of the object? For example, like so:
public class Container {
protected Champion champ;
public Container(Champion champ) {
this.champ = champ;
}
}
Now, make Champion an abstract class that contains the common methods for all the champions:
public abstract class Champion {
protected Something something;
abstract Something getSomething();
}
(Obviously, the variable/method shown here are just examples.) Then, have your individual Champion classes subclass Champion:
public class Blunder extends Champion {
public Something getSomething() {
return this.something;
}
}
Etc. Then, finally, do this:
public void initObjects() {
container = new Container(new Blunder());
}
Obviously, this is a basic example, and you don't have to take my advice. But it would probably be easier to do than the system you already had in AS3.
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
}
New to JAVA and Netbeans
My problem is that when I try to call a method from another class I get error:
"Cannot find symbol"
I do have import in calling class and tried every variation I could think of but the same error continues.
I copied the method into the calling class and the error disappears, but this is not useful since many classes will need to call this function.
Here are the specifics:
Created a test method in:
Calculators
|--Source Packages
|--schmidtjts.com.calculators
|--Functions_Conversion.java
package schmidtjts.com.calculators;
public class Functions_Conversion {
public static int test_lf(int Input) {
return Input * 10;
}
)
And then try to call it in:
Calculators
|--Source Packages
|--schmidtjts.com.calculators.ui.pages
|--Displacement.java
package schmidtjts.com.calculators.ui.pages;
import schmidtjts.com.calculators.Functions_Conversion;
public class Displacement extends javax.swing.JPanel {
public Displacement() {
initComponents();
}
private void testMethod() {
double ttt = test_lf(1);
}
}
I hope someone will have an idea, I have searched many problems with similar descriptions but not found a solution.
Tried deleting cache and restarting Netbeans.
UPDATE:
Your code should look like this:
package schmidtjts.com.calculators.ui.pages;
//This import below isn't that relevant.
import schmidtjts.com.calculators.Functions_Conversion;
public class Displacement extends javax.swing.JPanel {
public Displacement() {
initComponents();
}
private void testMethod() {
//Initialize an object that can be used to call the method
Functions_Conversion myObject = new Functions_Conversion();
//Then call the method using the object you've just created
myObject.test_If(1);
}
}
ORIGINAL ANSWER:
Try initializing an object like this:
//Initialize an object that can be used to call the method
Functions_Conversion myObject = new Functions_Conversion();
//Then call the method using the object you've just created
myObject.test_If(1);