I have a class called ArionFileExtractor in a .java file of the same name.
public class ArionFileExtractor {
public String ArionFileExtractor (String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
However, when I try to invoke ArionFileExtractor in another .java file, as follows:
String afe = ArionFileExtractor("gibberish.txt", "foo", "/foo");
NetBeans informs me that there are incompatible types and that java.lang.String is required. But I coded ArionFileExtractor to return the standard string type, which is java.lang.string.
I am wondering, can my ArionFileExtractor constructor legally return a String?
I very much appreciate any tips or pointers on what I'm doing wrong here.
Constructors create objects, they don't return data.
Your method, ArionFileExtractor(), is not a constructor. Consutructors do not have return types, and look like this:
public ArionFileExtractor (String fName, String startText, String endText) {
//...
}
Note the lack of a return type.
A constructor can only return an instance of object that it constructed - otherwise you have no reference against which to hang on to the object you just created! If you want to make a "utility" call, consider a static method:
public class ArionFileExtractor {
public static String getFileContents(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
Which can be invoked using
ArionFileExtractor.getFileContents(...)
As much as this is surprising, the code you made has a default no argument constructor. ArionFileExtractor is a method that returns a String. I was quite surprised when I first saw code that did this, as it is certainly an accident (as in your case).
You could call you method (just to show this is the case) with:
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
What it really sounds like you are trying to get at is a static method, not a class at all.
public class ArionFileExtractor() {
public static String extract(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
which you would call with:
String afe = ArionFileExtractor.extract("gibberish.txt", "foo", "/foo");
Constructor is not a regular method. It always returns instance of the class that it belongs to. In your example ArionFileExtractor. There is no way to return any other instance.
Notice that you can't specify return type for constructor explicitly nor use return keyword (illegal in this context).
Java compiler treats ArionFileExtractor as an instance method,
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
Constructor can only return instance of its class. It cannot return String.
For instance if you have class SampleClass, constructor can return only object of class SampleClass.
No it should not be able to legally return a String. I'm not sure why Netbeans didn't simply barf at you when you tried to. Maybe it tried to compile it as some sort of static method. Constructors do not generally have return types in code, because when they are compiled they are assigned to return an instance of the class they are constructing.
The easiest (though not necessarily best) way to adapt your code would be to have an empty constructor and turn the current constructor into a static method like this:
public class ArionFileExtractor {
private ArionFileExtractor() {}
public static String ExtractFile(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
The private constructor makes it so that ArionFileExtractor can only be used statically and cannot be instantiated. Then when you use it you simply do this:
String afe = ArionFileExtractor.ExtractFile("gibberish.txt", "foo", "/foo");
Be warned, using static classes is sometimes considered bad form - depending on the situation. So it might be worth while to try and come up with a different way to do this.
No.
A constructor does not really return anything. Instead it builds the object in question.
It looks like you want a utility method here:
public class Whatever {
public static String doStuff(String s) {
return s;
}
}
Yes.Only String class constructor can return string objects out of it ;).
This basically means that the constructor creates the object of the class you are calling.
You need to FIRST create the object (using the constructor) and THEN do stuff with it.
Java has very few smart shortcuts. I
Related
I want to ask about nested enums. I am working with old code and i found very strange construction that i not really good understand.
I have this enum :
public enum DbEngines {
ORACLE("oracle", "set define on", "set define off")
, POSTGRESQL("postgresql", "--TODO set define on", "--TODO set define off");
private final String dbEngine;
private String setOn;
private String setOff;
DbEngines(String dbEngine, String setOn, String setOff) {
this.dbEngine = dbEngine;
this.setOn = setOn;
this.setOff = setOff;
}
public String getSetOn() {
return setOn;
}
public String getSetOff() {
return setOff;
}
public String toString() {
return this.dbEngine;
}
}
I added private String to this enum, that are engine specific, so it is good place for me here. The problem is, that in some places in method declaration i see something like that
public someMethod(Enum<DbEngines> engine, ...)
And it worked perfectly without methods, but now, after changing, I couldn't call public getters of this enum. But if i change to :
public someMethod(DbEngines engine, ...)
it works without any problems with all public getters. Maybe someone could explain that?
Enum in Java is the base class for all enumeration types. One can think of it as similar to Object class.
Just like one can hold reference of object of any class using the reference of type Object, one can refer to an enumeration type using the reference of type Enum.
Object o = new Integer(10);
Enum e = DBEngine.ORACLE;
One cannot invoke a method present in inherited class but absent in superclass using the reference of superclass.
Similar explanation over here.
I have 2 classes: Rectangle and Circle.
Each of them implements the interface "JSONSerializable" with the methods "import" and "export".
In order to differentiate between the two classes the interface has a third method "getType" which simply returns "rectangle" or "circle" depending on the class.
This works fine and i get a JSON String which looks something like this:
{
type:rectangle,
points:[{1,2},{2,2},{2,1},{1,1}]
}
When i read the String again i need to decide which import method to call, depending on the type. What I did now is this:
public enum JSONType{
Rectangle(Rectangle.getStaticType()),
Circle(Circle.getStaticType());
private final String type;
JSONType(String type){
this.type = type;
}
public String getType(){
return type;
}
}
This works, i can then read the JSON-String and compare against all String types in my enum. However, I need to declare two methods (getType() and static getStaticType()) for every child objects, where both return the same String:
public static String getStaticType(){
return "rectangle";
}
public String getType(){
return Rectangle.getStaticType();
}
Is there any way around that? I think the answere is no, but I've never before had a situation like this. I'm happy for any design advice :)
Say I have this enum:
public class MyErrors {
public enum Errors {
BAD_FILE_PATH("Please point to a valid file");
private final String message;
Errors(final String message) {
this.message = message;
}
#Override
public String toString() {
return message;
}
}
And this call:
Logging.log(Level.INFO, MyErrors.Errors.BAD_FILE_PATH.toString());
It seems so verbose to me to have to call .toString(). Isn't there a way to just call the enum itself and have it return its string by default?
Ideally I'd like something like MyErrors.BAD_FILE_PATH --> which returns a string so it's not so verbose. Does that make any sense?
Both of these work for me in Eclipse:
LOG.info(Errors.BAD_FILE_PATH); // Using Log4j
System.out.println(Errors.BAD_FILE_PATH);
These two methods take an Object parameter. And since are not receiving Strings, the logic in those methods must call the toString() method on the passed in object to obtain a string.
The log() method of java.util.logging.Logger does not support an Object parameter. Instead, it is expecting a String parameter; thus, the logic in this method has no need to call toString().
What you are looking for is a new signature for the Logger that supports an Object parameter. However, I don't know that extending the Logger is a straight forward process or advisable; see here.
Another option would be to use Log4j.
For example:
Here Variable in class A
public class A{
public String aClassVar="hello";
}
Using it in Class B
A obj=new A();
String inBClass=obj.aClassVar;
but what about the other way around? How do I change String aClassVar from Class B? Can I pass Context from A to B constructor and then call aContext.aClassVar = ...?
public class A {
private String myField; //"private" means access to this is restricted
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}
}
Search Android getter and setter, you will have tons of links.
First of all, String is Immutable so you can not change the value of it , you can only assign its value into other string etc. Secondly static is used to access things globally throughout the program.
Define aClassVar as a static variable, then
A obj=new A();
obj.aClassVar="new string";
make aClassVar as static and use following code.
A objA=new A();
objA.aClassVar="new value";
or else use getter and setter method to change the values.
I am an intermediate Java programmer, and very often use methods that are able to take a target as a parameter. Methods such as:
String.substring();
String.indexOf();
So I was wondering, how do I create a method that can take a target String, etc.?
String.substring(); and String.indexOf(); are examples of instance methods of the String class. They are methods that act on objects of that class.
String is a final class in Java, and as such it can not be extended to add your own methods to it. You'll have to create your own class.
Perhaps, for example:
public class MyString {
private String s;
public new(String newValue) {
s = newValue;
}
public someNewMethod() {
//do stuff
}
}
Now, on object of your MyString class, you can do this...
MyString ms = new MyString("Hello World.");
ms.someNewMethod();