Declare objects in every method? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So I'm new to java, but I'm fluent in python, and I'm stuck on a basic problem. Do I have to declare an object in the same method in which I'm going to use it? Or is there a way to transfer objects from method to method? Thank you for your help (:

Transfer objects from method to method is generally the most recommended way. This helps keep code modular and reduces coupling. A common concept in Java is getters and setters for custom classes. See example below:
public class MyClass {
private String myString; // this variable can only be directly access from within MyClass scope.
// constructor - called when an instance of MyClass is initialized ( e.g. MyClass myClass = new MyClass(); )
public MyClass(){
myString = "Hello world!"; // init my_string
}
// Can access variable from within class to print
public void printMyString(){
System.out.println(myString);
}
// Can set private class variables
public void setMyString(String input){
this.myString = input; // set value
}
// Can get (return) private class variables
public String getMyString(){
return myString; // get value
}
}
From another section in your program:
MyClass myClass = new MyClass(); // init class (calls constructor)
System.out.println(myClass.getMyString()); // prints "Hello world!"
myClass.setMyString("Hola"); // changes value of myString
System.out.println(myClass.getMyString()); // prints "Hola"
System.out.println(myClass.myString); // Error: cannot directly access private variable of java class MyClass.

Variables which should be available across multiple methods should be declared at the top of the class as follows.
public class Test{
int number = 1;
String text = "hello";
public int method1() {
return number + 1;
}
public String method2() {
return text + " moo";
}
}
Alternatively, if you have another variable with the same name as one of the global variables you can refer to the global one with something like this.number

Related

What's the difference between calling a method with/without this keyword [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
When should I use "this" in a class?
(17 answers)
Closed 4 years ago.
I have a question.
Please don't mark it as duplicate, Go through the question once. I can't find an answer to this specific situation/condition, If you feel it has a specific answer then only mark duplicate. Marking it duplicate makes my question remain a question without an answer.
What's the difference between calling a method with/without this as a keyword. Which one is better?
The question specifically applies for a single class.
Please have a look at the sample code below to fully understand the question.
public class ThisSample {
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne();
}
public void methodOne() {
System.out.println("Method 1 called");
this.methodTwo(); //Line 1
methodTwo(); // Line 2
}
public void methodTwo() {
System.out.println("Method 2 called");
}
}
What difference (Advantage/disadvantage/implication) does the 2 lines (Line 1 & Line 2) in the code make?
Thanks & Regards,
Yadvendra
'This' task is to differentiate object property from method parameter. In presented code usage of this does nothing. However the most common use is like in this example:
public class Service {
private ServiceA serviceA;
private ServiceB serviceB;
// Here 'this' is used to make sure that class instance
// properties are filled with constructor parameters
public Service(ServiceA serviceA, ServiceB serviceB) {
this.serviceA = serviceA;
this.serviceB = serviceB;
}
}
this is used to specify that you're talking about the method methodTwo from the current instance of the class ThisSample.
If you'd have another class called AnotherSample:
public class AnotherSample{
public static void methodThree()
{
// some code
}
}
You could use the method methodThree by calling it as follows AnotherSample.methodThree();.
In summary: this just specifies that you're using the instance of the class you're currently coding in.
In the example, you have given, the difference is nothing. Let me modify your code a bit:
public class ThisSample {
int variable;
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne(3);
sample.methodTwo(5);
}
public void methodOne(int variable) {
this.variable = variable;
System.out.println("variable is: " + this.variable);
}
public void methodTwo(int variable) {
variable = variable;
System.out.println("variable is: " + this.variable);
}
}
Here, for method 2, you must use this.variable to set the value in the instance variable. Otherwise, both method will print 3 here. The second method is also printing three because you set 3 in method one.
Now in method 2, in
variable = variable
line, both variable are paramater of mathod 2. But when you are writing,
this.variable = variable;
you are telling, left one is instance variable of this object and right part is assigned to instance variable of this object.
Edit:
If you want to know "which is more preferred", then see this link too. Here using this is said "redundant". Link is: https://softwareengineering.stackexchange.com/a/113434/162116
Here, it is also said that, I should refactor the code if I actually need this to deduce the instance variable.

How do I make all instances in Java do something [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create a static method that moves all instances to the origin, but I can't use a static method on instance variables (like xPosition and yPosition).
Would I have to loop through all of the instances, or is there a way to do this with a static method?
Thanks in advance!
To ensure that you have all the instances of your class, I would prevent allowing to create the instances directly by making the constructors private and enforcing calling a static method to create and publish the instance, something like:
public class MyClass {
/**
* Thread-safe collection used to store all existing instances
*/
private static final Collection<MyClass> INSTANCES = new ConcurrentLinkedQueue<>();
private MyClass() {}
public static MyClass newInstance() {
// Create the instance
MyClass instance = new MyClass();
// Publish the instance
INSTANCES.add(instance);
return instance;
}
public static void release(MyClass instance) {
//Un-publish my instance
INSTANCES.remove(instance);
}
public static void releaseAll(Predicate<MyClass> predicate) {
//Un-publish all instances that match with the predicate
INSTANCES.stream().filter(predicate).forEach(INSTANCES::remove);
}
public static void apply(Consumer<MyClass> consumer) {
// Execute some code for each instance
INSTANCES.stream().forEach(consumer);
}
}
Then your code will be:
// Create my instance
MyClass myClass = MyClass.newInstance();
// Execute some code here
...
// Release the instance once the work is over to prevent a memory leak
MyClass.release(myClass);
...
// Execute some code on all instances
// Here it will print all instances
MyClass.apply(System.out::println);
...
// Release all instances that match with a given test
MyClass.releaseAll(myClass -> <Some Test Here>);
You can do it with a static method if you have a static registry of all the instances.
class YourClass {
static List<YourClass> instances = new ArrayList<>();
YourClass() {
instances.add(this); // Yuk! Unsafe publication.
}
static void moveAll() {
for (YourClass instance : instances) {
// Do something to instance.
}
}
}
But I'd recommend you don't do that, but instead have a non-static registry class:
class YourClassRegistry {
List<YourClass> instances = new ArrayList<>();
void add(YourClass instance) {
instances.add(instance);
}
void moveAll() {
for (YourClass instance : instances) {
// Do something to instance.
}
}
}
Example usage:
YourClassRegistry registry = new YourClassRegistry();
registry.add(new YourClass());
registry.add(new YourClass());
registry.add(new YourClass());
registry.moveAll();
This allows you to have separate groups of "instances", that you can move separately.
Global mutable state (like the static version of the registry) is a pain in the neck, reduces testability, requires more care with respect to thread safety etc.

How do I use "getter" methods (for beginners)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
When it comes to Java programming you'll stumble upon this along your way. Here is an elementary answer to help new programmer learn how to use a getter method without the terminology or complexity of people is this field.
By creating an accessor method (and not creating a mutator method).
public class MyClass {
public MyClass(int v) {
this.myField = v;
}
private int myField;
public int getMyField() {
return myField;
}
}
Then you can call that "getter" in some other class with an instance of MyClass.
public class SomeOtherClass {
public static void doSomething(MyClass my) {
System.out.println(my.getMyField());
}
public static void main(String[] args) {
doSomething(new MyClass(42)); // <-- for example.
}
}
When working with Java projects you'll stubble upon "getter" methods or "get" methods. This is how I solved my problems, by following these instructions.
If you're confused on why you should use "getter" methods follow this link.
Note that this is for beginners and the language/format I use
may (and in some cases is) not be proper.
Note that you will also need to have a general concept of Java.
This is for people who don't understand some of the Java terminology
Take a look at my (example) project set up.
Package Explorer/Setup
Project Name
src
(default package/package name)
Class1.java
Class2.java
Class 1
public class Class1 {
// creates an object
static Class2 class2 = new Class2();
public static void main(String[] args) {
// this will print our method (method1) in our class (Class2)
System.out.println(class2.method1());
}
}
Class 2
public class Class2 {
// this is the method we are accessing
public double method1(){
// this is what we are returning (sending back)
return 2.5;
}
}
Output (console)
2.5
So how do we access a "getter" method?
If you haven't noticed already, we printed it in our class "Class1" using...
System.out.println(class2.method1());
we used class2. because we created an object that allows us to access our Class2. Notice that class2 is lowercase and Class2 is uppercase, this is because class2 (lowercase) is the object we've created. Thus we are using the object to use our "getter" method not our class. We create our object using...
static Class2 class2 = new Class2();

"In java variables are initialized before any method is called, even the constructor.". – can anyone provide an example? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
"In java variables are initialized before any method is called, even the constructor.". That is, the class's constructor body runs after variable initialization. – can anyone provide an example with detailed explanation??
Any help would be appreciated.
This is not true. Maybe you heard that in the context of static variables, because:
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution .
These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object.
Example 1:
public class Test {
private final String s = "123";
public static void main(String[] args) {
Test t = new Test();
}
Test() {
System.out.println(s);
}
}
Here s is a class variable and can only be accessed by an instance(object) of the class. If you try printing its value in the main method, you won't be able to access the variable as it belongs to the class objects and objects only.
Example 2:
public class Test {
private static final String s = "123";
public static void main(String[] args) {
System.out.println("In main:" + s);
Test t = new Test();
}
Test() {
System.out.println(s);
}
}
In this case, the class variable is static which means that it can be accessed directly without creating any instance of the class; meaning, the variable does not belong to the objects.
This is precisely why the main method is static, as it needs to be called before any class objects have been created.

Is it good practice in Java for a class's method to redundantly return a modified global field of the class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it good practice in Java for a class's method to redundantly return a modified global field of that class?
Note: I edited the examples below to correct my code.
For example:
public class MyClass {
private String veryImportantString;
public static void main(String [] args) {
MyClass myObject = new MyClass();
myObject.fieldQuestion();
}
public void fieldQuestion() {
veryImportantString = "Hello, StackOverflow";
String newString = addStringToVeryImportantString(" World!");
System.out.println(newString);
}
public String addStringToVeryImportantString(String inputStr) {
this.veryImportantString = veryImportantString + inputStr;
return veryImportantString;
}
}
In the above example, addStringToVeryImportantString is returning veryImportantString, even though as a class field it has been modified and is globally available to the calling method.
In the below example, I do the same thing without returning the field:
public class MyClass {
private String veryImportantString;
public static void main(String [] args) {
MyClass myObject = new MyClass();
myObject.fieldQuestion();
}
public void fieldQuestion() {
veryImportantString = "Hello, StackOverflow";
addStringToVeryImportantString(" World!");
String newString = veryImportantString;
System.out.println(newString);
}
public void addStringToVeryImportantString(String inputStr) {
this.veryImportantString = veryImportantString + inputStr;
}
}
My question is: does it matter? Is there any difference in terms of coding standards, readability, efficiency, etc.? In a way, it makes sense to never return a global class field that a function has modified, because what is the point? The field is available anyway. On the other hand, maybe it makes sense to return the field in order to indicate that the primary purpose of the function is to modify that field and return the value.
Thanks for your input.
It is a usual coding standard for a method to either mutate an object (or variable) or get information about it but never both. Therefore a method that has a return will be assumed at first glance not to have any secondary effects (like changing veryImportantString). This is not a hard and fast rule and there are many reasons to break it but it should never be broken lightly.
Secondly the method signature in the second snippet (with a void return) could only reasonably do one thing; change veryImportantString. But with a return it could do two things; change veryImportantString and return it or return a seperate string based upon veryImportantString. As the void signature is less ambiguous it is preferable (unless theres a specific reason to do otherwise)
For your example, its not particularly important.
In general when you have a private piece of data and a public method. Your only way to get information out to the user of an instance of your class related to the private data is via returning something from a public method. Remember that most Java programs are much more complex and the need to return data related to a private field (java beans for instance) are much more common.

Categories