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).
Related
I know that the method would be protected not private if what I want to do was intended, however I want to make my own PriorityQueue that will need to call siftUp a few more times. I can't edit the declaration of the field as PriorityQueue is a part of the java library, so I'm looking for another way to call it. Is the only thing I can do copy the whole class from the library and change it to my needs?
There is no way to override the superclass's private method, unfortunately.
According to Oracle's documentation on Controlling Access to Members of a Class, the private method is only for the class itself to access.
Here's the table of the Superclass's visibility to Subclass:
I believe they offer the developers to implement the "least privilege" principle by offering the private visibility so there would be no way for it to be accessible anywhere outside the class it was created in.
If you wanted to be able to override it, you should make it protected or don't give it any modifier (considered "Package access" level).
Here is an example:
package this.silly.package;
public class Foo() {
void thisAction() {
// do stuff...
}
private void somethingElse() {
// Do secret stuff.
}
}
package this.silly.package;
public class Bar extends Foo() {
// This will work
// because this class is in the same package as Foo.
#Override
void thisAction() {
// Do something else
}
// This will not work
// because Foo made this method private,
// so it is only accessible by Foo.
#Override
private void somethingElse() {
// Please don't do secret stuff. You might drive me crazy!
}
}
I am using a generator for my project. Problem is now I need to modify this library's some methods according to my needs.
Generator class is final so I can't create a new class that extends it. Also putlast method is private.
Is there a way to solve this problem or I need to remove this library?
My main method;
generator.setFlowProperty(myProperty);
Library classes;
public final class Generator{
public Builder setFlowProperty(Property property) {
putLast("flowProperty", property.toCustomString());
....
}
private Builder putLast(String name, String value) {
....
}
}
public final class Property{
public String toCustomString(){
return "a" + prop; // I want to modify this and return "b"+ instead of "a"+.
}
}
There is no way you can inherit final class. I suppose library author made Generator class not for overriding. Anyway you can create your own class with logic you want.
If you want to override only a few functionalties of the library and leave most of them as they are, you can create a class that wraps the library class, only modifying the desired behaviours. So, the main purpose of this class will be to serve as a proxy before the library class, except when you want to modify some behaviour.
i have my DTO class that is :
public class EmailResponse {
// Make public to avoid getters and setters
public Email email;
public RequestData reqData;
public EmailResponse() {
super();
}
}
and i want to implement to it this interface:
public interface IAssertionErrorDo {
public void onErrorDo();
}
but i want to do it during execution, i don't want to touch "EmailResponse" because it would not be ok to make it implements that interface due they don't belong to the same layer, i mean, EmailResponse would belong to service layer and IAssertionError would belong to test layer. I am using TestNG.
Do you know how i could do this? Regards
EDIT:
My implementation is this:
EmailResponse emailResponse = emailService.getUserEmail(userId);
And the reason i want to do this "injection" is because i have
public class LoggingAssert
extends Assertion {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAssert.class);
private IAssertionErrorDo dataE;
#Override
public void onAssertFailure(IAssert a, AssertionError ex) {
LOGGER.info("[ERROR] " + a.getMessage());
if (this.dataE != null) {
this.dataE.onErrorDo();
}
}
public LoggingAssert setOnErrorDo(IAssertionErrorDo object) {
this.object = object;
return this;
}
}
loggingAssert.setOnErrorDo(emailResponse).assertNotNull(emailResponse.getEmail().getId(),
"Checking created email doesn't exists");
So i want to if assert fails execute method onErrorDo() from emailResponse
You could do
public class MyEmailResponse extends EmailResponse implements IAssertionErrorDo {
...
}
implementation calls in interfaces, you can call more than 1 interface if you want by adding commas to separate them..
to call interface methods you simply just use the method's name.
like this:
public class MyEmailResponse implements IAssertionErrorDo
{
public void onErrorDo() {//define it's behavior}
}
if you extend a class you use:
super.MyMethod()
to call the a method inside the extended class, but if you already have an extended class and want a method from another class you have to create an object for that class first then call it, thus:
MyClass mc = new MyClass();
if it is in a different package then
myPackage.MyClass mc = new myPackage.MyClass();
then you call your method from that class using the object you created, which is in this case mc.. so:
mc.MyMethod();
if you want it to return a variable then you will need to add a return statement in that method with the variable you want it to return.
interfaces are usually used for global an changing environments (dynamics), for example if you developed a program and it needs a driver to connect to databases then you will make an interface and send it to the database developers, and each one will fill the codes in that interface and send it back... this guarantees consistency.
when you implement an interface you have to define every method inside it (even if you leave it empty) and you cannot change the interface's methods names nor add... it is used in other areas as well, i don't think you need to use it in your case.
I am working on a series of classes that all inherit from a single, base, abstract class.
In order to keep track of all of these child classes, I'd like to implement something like a GUID -- for my purposes, it doesn't have to be an actual GUID, just an int that is unique to each instance of a child class. An incremented int is what I'd been hoping to use.
What I'd have liked to do, is implement the following in my abstract class:
abstract class ParentObject{
static int GUID = 0;
//other stuff
}
whereafter each child class, in its constructor, would have myGUID = GUID++;
However, whenever I try this, I get the following error from the Processing IDE:
The field GUID cannot be declared static; static fields can only be
declared in static or top-level types.
Because of how Processing handles class files (everything is an inner class), I can't have static class members. What are my options to duplicate this functionality in other ways?
Edit: This is being done in Processing and the Processing IDE. The ParentObject class is in its own processing file.
Edite2: I have learned that the reason Processing is different from Java is that all Processing classes are Inner Classes. Because of this, I have re-added the Java tag and reformulated the question.
Well, then face it. You can't do it. If you REALLY need it, declare an outer class for handling this piece of code, and call it in the top-level class's constructor.
If you MUST use this hierarchy of innerclass, then you can't do it. Java won't accept it in the way you wan't. You could declare your abstract class as static.
static abstract class ParentObject {
private static int GUID = 0;
}
But I'm almost sure this won't work for you either. So, I suggest to create a new outer class somewhere else to handle it.
public class GUID {
private static int GUID = 0;
public synchronized static void increment() {
GUID++;
}
}
abstract class ParentObject {
ParentObject() {
GUID.increment();
// constructor's stuff
}
}
This may speed down your app (depending on how often you instantiate a class), but not in a significant way.
a static protected method getNextGUID() would work
public abstract class ParentObject{
private static int GUID = 0;
protected static int getNextGUID(){
return GUID++;
}
//other stuff
}
don't forget to synchronize it/use AtomicInteger when you have multiple threads
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.