This question already has answers here:
How to instantiate an object in java?
(7 answers)
Closed 5 years ago.
Currently I'm following java course and I am struggling with a part of the code which I see used a lot in methods. So here goes:
Answer answer = new Answer("something");
I have a class named Answer and I think the first Answer is in reference to that. the lower cased answer is the variable. It's after the = sign I'm struggling to comprehend. any help please?
This declares a variable answer of type Answer and initializes it with a new object instance of class Answer by calling the Answer(String) constructor.
Consider Apollo's comment and google it.
This is not only a java principle but a generall programming principle.
You're creating a new Answer Object.
Let's look at this example:
public class Answer{ // The class
private String answer; // internal variable only visible for the class
public Answer(String answer){ // This is a constructor
this.answer = answer; // Here we assign the String we gave this object to an internal variable
}
public void setAnswer(String answer){ // Setter
this.answer = answer;
}
public String getAnswer(){ // Getter
return answer;
}
}
So now you have a class/Object named Answer.
When you now want to use it you need to create a new Object.
This is done over the constructor of a class. ( Constructor = basically a definition of what you need to create the Object )
First you declare what Object you want your variable to be, then you give the variable a name you can use it under.
That looks like this:
Answer variableName
But this will not create a new object.
To create it we need to give the keyword new in combination of a Constructor of the object we want to create.
As we defined a constructor that needs a String to create this object we need to call it like this:
new Answer("the string");
If we combine those two we finally have our usable new variable of a new create Answer
Answer yourVariable = new Answer("the string");
Any declaration in Java follows the following rules:
[variable type] [variable name] = [value];
So in your case:
variable type = object of type Answer
variable name = answer
value = new Answer("something")
What you're doing with new Answer("something") is that you're creating a new object of type Answer using the constructor that accepts a single String
Notice that the value is optional. You can just declare any value and assign a value after that
This is a pretty basic concept in Java.
Once we define a Java class, we can create objects of such class. To do so, we need to call a special method in the class, called constructor, with the reserved keyword new. Additionally, we want to store a reference to the newly created object in a variable, so that we can use it later.
To do so, we first declare a variable of the type of the class:
MyClass myVariable;
And then create an object and assign it to the variable:
myVariable = new MyClass();
In your case, the constructor receives one parameter of type String for initializing the object.
Related
I need help I need to know if Java allows to create an object dynamically, using the value of a variable.
Example
// I have 2 classes:
public class Audit {
private Long idAudit
// constructors, get and set
}
publish class Example {
private Long idExample
// constructors, get and set
}
-------------------------------------------------- -----
// create Audit and Example class object
Audit objAudit = new Audit ();
Example objExample = new Example ();
my question is the following can you create an object either of type Audit or example using the value of a variable as I try to do in the following example. Example:
String className = "Audit"; // variable that contains the class of the Object to create
className auditObject = new ClassName (); // I use the variable classname to create the desired object
Clearly I get an error trying to create the object that way, my question is can I create an object dynamically or some other option to try to achieve what I need. Thank you
Reflection is what you are searching for
final String className = "Audit";
final Class<?> clazz = Class.forName(className);
final Object o = clazz.getConstructor().newInstance();
There are several ways you can do this.
One is called reflection, and I will let you read about it on your own.
The other one is called a factory pattern. You can create a class called ObjectFactory. in that class you will have a method public Object createObject(String type).
In the method you can check if the type you received is one of your known types, and based on the type you can create the instance of the correct class. It is better of your classes implement the same interface. Then of course your method would return the instance of that interface (or a common base class).
Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:
public static final String TTT = (String) getText(R.string.TTT);
This is the error message:
Error: Cannot make a static reference to the non-static method getText(int) from the type
Context
How is this caused and how can I solve it?
Since getText() is non-static you cannot call it from a static method.
To understand why, you have to understand the difference between the two.
Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:
SomeClass myObject = new SomeClass();
To call an instance method, you call it on the instance (myObject):
myObject.getText(...)
However a static method/field can be called only on the type directly, say like this:
The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.
... = SomeClass.final
And the two cannot work together as they operate on different data spaces (instance data and class data)
Let me try and explain. Consider this class (psuedocode):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
Now I have the following use case:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
What are the values?
Well
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
So the question is why is TTT static or why is getText() not static?
Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?
There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.
A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity:
NonActivity.doStuff(this);
This will allow you to access your String resource without needing to use a public static field.
for others that find this in the search:
I often get this one when I accidentally call a function using the class name rather than the object name. This typically happens because i give them too similar names : P
ie:
MyClass myclass = new MyClass();
// then later
MyClass.someFunction();
This is obviously a static method. (good for somethings)
But what i really wanted to do (in most cases was)
myclass.someFunction();
It's such a silly mistake, but every couple of months, i waste about 30 mins messing with vars in the "MyClass" definitions to work out what im doing wrong when really, its just a typo.
Funny note: stack overflow highlights the syntax to make the mistake really obvious here.
You can either make your variable non static
public final String TTT = (String) getText(R.string.TTT);
or make the "getText" method static (if at all possible)
getText is a member of the your Activity so it must be called when "this" exists. Your static variable is initialized when your class is loaded before your Activity is created.
Since you want the variable to be initialized from a Resource string then it cannot be static. If you want it to be static you can initialize it with the String value.
You can not make reference to static variable from non-static method.
To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only.
Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
This question is not new and existing answers give some good theoretical background. I just want to add a more pragmatic answer.
getText is a method of the Context abstract class and in order to call it, one needs an instance of its subclass (Activity, Service, Application or other). The problem is, that the public static final variables are initialized before any instance of Context is created.
There are several ways to solve this:
Make the variable a member variable (field) of the Activity or other subclass of Context by removing the static modifier and placing it within the class body;
Keep it static and delay the initialization to a later point (e.g. in the onCreate method);
Make it a local variable in the place of actual usage.
Yes u can make call on non-static method into static method because we need to remember first' we can create an object that's class we can call easyly on non -static method into static mathod
This question already has answers here:
String s = new String("xyz"). How many objects has been made after this line of code execute?
(21 answers)
Closed 5 years ago.
The title says it all
String a;
String b = new String("Hello");
I've seen a lot of questions like this but none of them had Strings that weren't initiated yet.
Can someone help me on this ?
Thank you.
You are creating a single object that is referenced by variable b, a is a declared variable without any data assigned to it, that is not an object in a Java sense
First row only declares a string variable, but doesn't create object. In the second row, a string object is created with a new keyword.
So there's only one object created.
Here is an explanation took from OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam:
An object comes into the picture when you use the keyword operator new.
You can initialize a reference variable with this object. Note the difference between declaring a variable and initializing it. The following is an example of a class Person and another class ObjectLifeCycle:
class Person {}
class ObjectLifeCycle {
Person person;
}
In the previous code, no objects of class Person are created in the class ObjectLife-Cycle; it declares only a variable of type Person. An object is created when a reference variable is initialized:
class ObjectLifeCycle2 {
Person person = new Person();
}
Syntactically, an object comes into being by using the new operator. Because
Strings can also be initialized using the = operator, the following code is a valid example of String objects being created
class ObjectLifeCycle3 {
String obj1 = new String("eJava");
String obj2 = "Guru";
}
This question already has answers here:
What does "this" point to?
(5 answers)
Closed 4 years ago.
public class CommandForm extends Form implements CommandListener {
Display d;
public CommandForm(String msg) {
super(msg);
this.addCommand(exit);
}
private void showMessage(String title, String text) {
Alert a = new Alert(title, text, null, AlertType.INFO);
d.setCurrent(a, this);
}
public void prepare_view(Display d){
this.setCommandListener(this);
this.d = d;
}
public void show_view(){
d.setCurrent(this);
}
}
I do not know exactly what the 'this' keyword means in this example. My lecturer says it is the current object, when I inquire further, he said it is the CommandForm. Is that correct? When you pass in 'this' into a parenthesis, e.g setCommandListener(this) are you actually passing the CommandForm? The only way I know how to use 'this' is like this way, this.d = d. So this is kinda new to me.
He's right. If you call setCommandListener(this) you are passing a reference to the current object into the method. When you do this.d = d you are setting the variable d which is part of the class (i.e this) to the incoming value (in parenthesis).
Your lecturer is indeed correct. It's the current object, and this is simply a means to refer to the object currently in scope.
You use the keyword to pass the reference to other objects e.g. object.doSomethingWith(this), and/or resolve ambiguity between members and variables (e.g. this.x = x - there are two different xs here).
Check out the Java Language Specification section on 'this'.
Yes, the this keyword is a reference to that particular instance of the CommandForm class.
I have the following code that I am trying to understand:
public class A {
enum Size {S, M, L };
Size size = Size.M;
}
I understand the first enum line is creating an enum with three values but what is the second line doing? What will the variable size hold and is this another way to construct an enum?
The second line is just giving to the field size (of type Size) of the instance of class A the initial value Size.M.
You may be a little disturbed here by the fact that the enum is created inside the class A, it could have been in another file (but it's perfectly OK to put it inside the class A if it's used only there).
EDIT (not really part of the answer) : here's a (not pretty) exemple of enum declaration so that you can better understand the form of an enum declaration :
public enum QueryError {
no_request("no_request", "No request in client call"),
no_alias_requested("no_alias_requested", "no alias requested"),
session_not_found("session_not_found", "wrong session id"),
synosteelQuery_not_found("sxxx_not_found", "sxxx not found");
public JsonpServerResponse.Error error;
private QueryError(String type, String details) {
this.error = new JsonpServerResponse.Error();
this.error.type = type;
this.error.detail = details;
}
}
The second like is declaring a package private member variable of type Size in your class A and initializing it to point to Size.M.
An enum is a type (just as a class is a type). The second line is creating an instance variable called size, which has a type of Size (since an enum is a type). Then it's initializing the value of that instance variable to an instance of the enum Size (specifically, the Size.M instance).