Get a variable from an abstract class - java

Basicly i want to get the name of the map that is played from the "World.class", in a string on my main mod class...
public abstract class World implements IBlockAccess{
protected WorldInfo worldInfo;
//=====OtherStuff=====
public World(ISaveHandler par1ISaveHandler, String par2Str, WorldSettings par3WorldSettings, WorldProvider par4WorldProvider, Profiler par5Profiler, ILogAgent par6ILogAgent)
{
this.worldInfo.setWorldName(par2Str);
}
//=====OtherStuff=====
}
i created a class in the same package with this one
public class World_Spy extends World{
public World_Spy(ISaveHandler par1iSaveHandler, String par2Str,
WorldProvider par3WorldProvider, WorldSettings par4WorldSettings,
Profiler par5Profiler, ILogAgent par6iLogAgent) {
super(par1iSaveHandler, par2Str, par3WorldProvider, par4WorldSettings,
par5Profiler, par6iLogAgent);
}
#Override
protected IChunkProvider createChunkProvider() {
return null;
}
#Override
public Entity getEntityByID(int i) {
return null;
}
String TheName = "";
public void gotIt(){
TheName = this.worldInfo.getWorldName();
System.out.println(TheName);
}
}
and i call it from my main class with:
World_Spy WName = new World_Spy(null, null, null, null, null, null);
but it chrashes on startup...
any ideas?

World is not a static class... you need an instance of a World compatible object to get the name. One way to get an instance of a World and then the name:
World world = Minecraft.getMinecraft().isIntegratedServerRunning() ? mc.getIntegratedServer().worldServerForDimension(Minecraft.getMinecraft().thePlayer.dimension) : Minecraft.getMinecraft().theWorld;
String worldName = world.getWorldInfo().getWorldName();
This code should work client-side.

You have not initalized worldInfo
protected WorldInfo worldInfo; // initialization MISSING!
So, when you try to instantiate World_Spy which in turn calls its parent class constructor World() you get a NullPointerException at
this.worldInfo.setWorldName(par2Str); // NullPointerException here
To resolve the issue simply provide an instance
protected WorldInfo worldInfo = new WorldInfo();

I believe it "crashes" by throwing NullPointerException here:
this.worldInfo.setWorldName(par2Str);
Indeed variable worldInfo was never initialized by you try to call its method setWorldName(). Since the variable is null at this point throwing NullPointerException sounds reasonable.
In java (exactly like in all other programming languages I know) you have to initialize variable before using it. Indeed primitive types are initialized by default using some kind of "normal" value. However variables of custom types are initialized to null that may confuse beginners.
To initialize you have to use new keyword following by constructor call:
worldInfo = new WorldInfo();
now you can call setters and other methods of worldInfo.

Related

Null Pointer Exception in Java Enum

I'm learning Enum concept in java and I faced a problem while practicing.
Here is the code snippet,
public class MyClass {
private String cardColor = CARDS.SPADE.cardColor; #Causes Null Pointer #Default Value
private MyClass(CARDS card){
this.cardColor = card.cardColor;
}
public static enum CARDS{
SPADE("Black"),
CLUB("Black"),
DIAMOND("Red"),
HEART("Red");
private String cardColor = null;
private MyClass obj = null;
CARDS(String color){
this.cardColor = color;
obj = new MyClass(this); #Trying to create object for MyClass
}
public String getCardColor(){
return this.cardColor;
}
}
public static void main(String args[]) {
System.out.println(CARDS.SPADE);
}
}
I'm trying to create a MyClass object private to the enum in it's constructor. Here the value CARDS.SPADE is null and I end up with Null Pointer Exception.
If I don't create an object in enum constructor everything works perfect,
obj = new MyClass(this);
I'm not understanding why the static enum is not initialized and I'm confused with the control flow here. Can someone explain me what's wrong here?
You have a circular dependency : the initialization of the CARDS enum and the MyClass instance depend on each other.
CARDS constructor instantiates MyClass but MyClass constructor relies itself on the CARDS.SPADE state that is not still fully initialized as in the pending enum constructor.
Either break this cycle or do things in two times. Init the enum without the bidirectional relationship and after the constructor invocations, set the enum value to the MyClass instance via a setter.
Note that the "real" cause of the NullPointerException is that you don't refer to the currently instance created in the enum constructor (this) but you refer the enum value from the enum class itself : MyClass.CARD.SPADE.
The first has a state but the second not yet since the enum constructor has not returned yet.
By passing the enum instance into the constructor of MyClass it will "work" :
CARDS(String color){
this.cardColor = color;
obj = new MyClass(this);
}
}
// ...
public MyClass(CARDS cards){
cardColor = cards.cardColor;
}
But in a general way, passing this during constructor body to another object/class not a good idea. This may leak to an inconsistent state if the object states changes between this time and the end of the constructor invocation.

Instantiate public object inside method

I'm trying to instantiate an object inside a method of a class so it can be used anywhere in the class. I come from a python background and it is quite easy, you can just pass the instantiated object to an instance of it's "self" like below.
self.camera = CameraInstance()
How do you do this in Java? I tried something like below but it doesn't like it.
private void init_camera_settings() {
public CameraInterface camera;
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
Both methods are in the same class. The reason for this is because I only want to instantiate the camera object only in certain scenarios.
Thanks!
You can't declare a field inside a method. In Java, a type either has a field, or it doesn't. Every instance of the same class has the same set of fields.
But you can declare the field (not in a method) and decide to only assign a value to it in a method:
// Note: avoid public fields
public CameraInterface camera;
private void initCameraSettings() {
camera = new Camera();
}
private void someotherMethod() {
camera.takePhoto();
}
(The field will have a default value, in this case null, until you assign a different value to it.)
As an aside, I'd strongly advise against public fields. I make every field private, and add properties to allow access where necessary. This allows you to change implementation details later. The one exception to this is public static final fields of immutable types, basically for constants, but even there I'd be cautious.
To use the variable throughout the class in different methodsm the variables should have class scope. You usually use new to create a new Object
public MyClass {
public CameraInterface camera = new Camera ();
private void init_camera_settings() {
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
}
self.camera = CameraInstance()
is equivalent to:
class Foo {
private CameraInstance camera;
public Foo() {
this.camera = new CameraInstance();
}
// use "this.camera" in methods.
}

Setter Method of Bean Class

Hello Friends Iam trying to call Setter method from other Setter method but iam getting nullPointerException in that. Is possible to call setter method from other setter.
Here is my bean class:-
public class ApplicationParameterListEntityTo{
private Long statusValueID;
private WidgetFieldValueBean1 parameterListStatusValueID;
public Long getStatusValueID() {
return statusValueID;
}
public void setStatusValueID(Long statusValueID){
this.statusValueID = statusValueID;
this.parameterListStatusValueID.setWidgetFieldValueID(statusValueID);
}
public WidgetFieldValueBean1 getParameterListStatusValueID() {
return parameterListStatusValueID;
}
Is there any problem in this peace of code.
The following line probably is giving you null pointer
this.parameterListStatusValueID.setWidgetFieldValueID(statusValueID);
Because, the WidgetFieldValueBean1 parameterListStatusValueID object is not initialized before you are calling the setWidgetFieldValueId method
You need to do something like
this.parameterListStatusValueID = new WidgetFieldValueBean1 ();//Considering it has a default constructor
this.parameterListStatusValueID.setWidgetFieldValueID(statusValueID);
Take a look at your setStatusValueID method. Since parameterListStatusValueID is never initialized, it is null, and thus every access to it (like this method, e.g., does), will result in a NullPointerExcetpion.
One way to solve this would be to initialize it in the definition:
public class ApplicationParameterListEntityTo {
private Long statusValueID;
private WidgetFieldValueBean1 parameterListStatusValueID = new WidgetFieldValueBean1();
...
You need to init the member variable parameterListStatusValueID, such as:
private WidgetFieldValueBean1 parameterListStatusValueID = new WidgetFieldValueBean1();

How to read a variable from an abstract class?

is it posible to read the "worldInfo" from another class ?
the following is part of the class that holds it:
public abstract class World implements IBlockAccess{
protected WorldInfo worldInfo;
//=====Stuff=====
public World(ISaveHandler par1ISaveHandler, String par2Str, WorldSettings par3WorldSettings, WorldProvider par4WorldProvider, Profiler par5Profiler, ILogAgent par6ILogAgent)
{
this.worldInfo.setWorldName(par2Str);
}
}
i want to use it in my class to get the name. "worldInfo.getWorldName"
EDIT 1:
Ok i created a class in the same package with the World.. "World_Spy.class"
public class World_Spy extends World{
public World_Spy(ISaveHandler par1iSaveHandler, String par2Str,
WorldProvider par3WorldProvider, WorldSettings par4WorldSettings,
Profiler par5Profiler, ILogAgent par6iLogAgent) {
super(par1iSaveHandler, par2Str, par3WorldProvider, par4WorldSettings,
par5Profiler, par6iLogAgent);
}
#Override
protected IChunkProvider createChunkProvider() {
return null;
}
#Override
public Entity getEntityByID(int i) {
return null;
}
String TheName = "";
public void gotIt(){
TheName = this.worldInfo.getWorldName();
System.out.println(TheName);
}
}
But when i call it from the main class it crashes the game..
World_Spy WName = new World_Spy(null, null, null, null, null, null);
Is it about the parameters?
In order to access worldInfo you'll have to extend World but as worldName is set to the second parameter of World constructor, it means you have to know it in your child class, so ..
For the functionality you want, either change the keyword protected to public, or create a public function in the class. It would look something like this:
public String getWorldName(){
this.worldInfo.getWorldName();
}
Actually, protected means it can be used by childclasses but also by any other class in the same package. So yes, you can use it by all classes in the same package even if they're not subclassing the abstract class
The class is abstract, so it cannot be initiated. You can read static variables from this class, but you cannot create object of this class. You can make this variabale as static and then you read it or inherit this class and make object of it or make it non-abstract and make object of it.
This variable holds constant? Make it static.
The field can be accessed directly if one of the following is true:
That another class extends World (inherited protected fields are
visible in derived classes, also World is not final and has non private constructor)
That another class belongs to the same package (protected fields are
visible in classes from the same package, same as package private).
The field can also be accessed through reflection from any other class after setting accessible property to true on that field (as long as security manager permits).

Accessing data from a data class returning null

OK, I'm not super new to java but for some odd reason I can't figure out why this is not working for me. Basically I have 3 classes in my applet.
My main, my string constructor, and my data class.
The main class calls the string constructor, the string constructor stores its final product into the data class. Last, I'm trying to access the data class using my Main class.
The returned value to the main is always null and I can't figure out why. My suspicion is I'm somehow creating 2 separate data class objects but Ive looked at examples of code and it all seems correct. Here are the classes..
main.
public class LaneGUI extends javax.swing.JApplet {
private laneData laneData;
Timer timer;
/** Initializes the applet LaneGUI */
public void init() {
laneData = new laneData();
xmlParser.parseInputString(connection.getFinalXMLString());
System.out.println(laneData.getLaneID());
string contructor...
public class XMLParser {
private laneData laneData;
public void parseInputString(String input){
try{
/*some xmlparsing*/
laneData = new laneData();
laneData.setLaneID(string);
data class
public class laneData {
private String laneID;
public String getLaneID() {
return laneID;
}
public void setLaneID(String laneID) {
this.laneID = laneID;
}
}
There is a lot of editing here, like in the string class I took out all of the xml parsing and string editing.
Basically, when i check the getLaneID after i set it in the string constructor the value is correct. But when i call a get from the main, its null.
XMLParser and LaneGUI are referring to two different instances of laneData.
Instead of your final line in LaneGUI, which says this:
System.out.println(laneData.getLaneID());
You need something like this:
System.out.println(xmlParser.getLaneData().getLaneID());
You'll also, of couse, need to add a getLaneData() to XMLParser that returns it's laneData instance (or a deep copy thereof.)
As you rightly speculated, you have two different instances of laneData. The XMLParser class has a local instance of laneData different from the instance referenced by LaneGUI.

Categories

Resources