set variable in calling object from object being called - java

In Java, how do you set variables in a calling object from the object that is being called? I guess I could set up some kind of struct class, but can someone show me if there is a simpler way to do it, such as some modification of the pseudocode below:
public class Example(){
int thisInt;
int thatInt;
public static void main(String[] args){
Another myAnother = new Another();
}
setThisInt(int input){thisInt=input;}
setThatInt(int input2){thatInt=input2;}
}
public class Another(){
void someFunc(){
this.Example.setThisInt(5);//I know this syntax is wrong
this.Example.setThatInt(2);//I know this syntax is wrong
}
}

Pass in a reference to the object.
public class Another{
void someFunc(Example ob){
ob.setThisInt(5);
ob.setThatInt(2);
}
}
If you're using nested classes(one class inside the other with an implied parent-child relationship), use:
OuterClass.this.setThisInt(5);
and so on.

Related

Why make an object for Main class, for the methods to work?

I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!

Unable to access variables in different classes

package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(prizes[1]);
}
}
I'm trying to access the array 'prizes' in a different class, but it keeps saying that 'prizes' cannot be resolved. If you could tell me how to fix this that would be great.
If you are referencing a static field in another class you will need to use the name of that class to reference the field, so basically you need to change your main to this:
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
This is called a namespacing issue. Let's pretend you could do what you're trying to do. What if you make another class called Prizes2 and put another variable in it, also named prizes? How does RunPennyPinch know which prizes variable it should be using?
Perhaps you could solve this problem by saying, "only one prizes variable is allowed to exist in any program at one time". If this were a real limitation, you would quickly run out of meaningful names to give to variables.
The solution that Java came up with is namespacing: To give a variable a context it lives in. Two variables can have the same name, but as long as they have a different context, they won't clash. The price you pay is you have to tell the program which context you want to use when you're referring to a variable.
Here's how to fix the problem:
package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
//===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
There's something else you should know: If you don't explicitly state a context, it defaults to using this as the context. As an unrelated example, these two methods do the same thing and both work:
package foo;
public class Bar {
public String baz = "Puzzle";
public void impliedThis() {
System.out.println(baz);
}
public void explicitThis() {
System.out.println(this.baz);
}
}
You have to prefix the variable with the class name as the variable is not within the RunPennyPinch class.
System.out.print(Prizes.prizes[1]);
You may also have to import the Prizes class, depending on your set-up.
The variable itself doesn't exist in that context. It's a static member of another class. So you need a reference to that class:
System.out.print(Prizes.prizes[1]);
The main advantage of static is that you dont have to create an object to access that variable. You just have to call that variable by Classname.variablename (Classname is the name of class in which that variable was present)
System.out.print(Prizes.prizes[1]);

Is it possible for a static method to refer to "this" in Java?

I am new to Java. I know static is class level and this is object level but please let me know if a static method can refer to the this pointer in java?
No it does not make sense to refer this in static methods/blocks. Static methods can be called without creating an instance hence this cannot be used to refer instance fields.
If you try to put this in a static method, compiler will throw an error saying
cannot use this in static context
No, this cannot be accessed in a static context. June Ahsan said everything that you probably need to know but I would like to add a little background.
The only difference between an object method and a static method on byte code level is an extra first parameter for object methods. This parameter can be accessed through this.
Since this parameter is missing for static methods, there is no this.
Example:
class MyClass {
private int b;
public void myMethod(int a){
System.out.println(this.b + a);
}
public static void myStaticMethod(int a){
System.out.println(a*a); // no access to b
}
}
on byte code level becomes (roughly speaking, because byte code does not look like this)
class MyClass {
int b;
}
void myMethod(MyClass this, int a){
System.out.println(this.b + a);
}
static void myStaticMethod(int a){
System.out.println(a*a); // no access to b
}
No but you can create a static object of you class in your class like this
private static ClassName instance; and then you can set it with instance = this; in the constructor. this will then be available for you to use in a static method.

Static And Non Static Method Intercall In Java

I am clearing my concepts on Java. My knowledge about Java is on far begineer side, so kindly bear with me.
I am trying to understand static method and non static method intercalls. I know --
Static method can call another static method simply by its name within same class.
Static method can call another non staic method of same class only after creating instance of the class.
Non static method can call another static method of same class simply by way of classname.methodname - No sure if this correct ?
My Question is about non static method call to another non staic method of same class. In class declaration, when we declare all methods, can we call another non static method of same class from a non static class ?
Please explain with example. Thank you.
Your #3, is correct, you can call static methods from non-static methods by using classname.methodname.
And your question seems to be asking if you can call non-static methods in a class from other non-static methods, which is also possible (and also the most commonly seen).
For example:
public class Foo {
public Foo() {
firstMethod();
Foo.staticMethod(); //this is valid
staticMethod(); //this is also valid, you don't need to declare the class name because it's already in this class. If you were calling "staticMethod" from another class, you would have to prefix it with this class name, Foo
}
public void firstMethod() {
System.out.println("This is a non-static method being called from the constructor.");
secondMethod();
}
public void secondMethod() {
System.out.println("This is another non-static method being called from a non-static method");
}
public static void staticMethod() {
System.out.println("This is the static method, staticMethod");
}
}
A method is and should be in the first regard be semantically bound to either the class or the instance.
A List of something has a length or size, so you ask for the size of special List. You need an object of that class to call .size ().
A typical, well known example of a static method is Integer.parseInt ("123");. You don't have an Integer instance in that moment, but want to create one.
If, at all, we would bind that method to an instance, we would bind it to a String instance - that would make sense:
int a = "123".parseInt ();
That would have been a reasonable choice, but it would mean that similar methods for float, double, long, short, Boolean and maybe every class which has a symmetric "toString" method would have to be put into String. That would have meant a zillion of extensions to the String class.
Instead String is final, so a reasonable place to put such a method is the target class, like Integer, Float and so on.
not sure that I understand the question correctly, but non-static methods are the standard way to design classes in OO. Maybe this sample will help spark the discussion:
public class MySampleClass{
private void methodA(){
System.out.println('a called');
}
public void methodB(){
this.methodA();
staticMethod(this);
}
private static void staticMethod( MySampleClass inst ){
inst.methodA();
}
}
You can call non-static method from non-static method using explicitly reference to object on which you want to call that method someObject.method, or without specifying that object someMethod() (in this case it will be invoked on same object that you are invoking current non-static method).
Maybe this will show it better
class Demo {
private String name;
public Demo(String n) {
name = n;
}
public String getName() {// non static method
return name;
}
public void test(Demo d) {// non-static method
System.out.println("this object name is: "+getName());// invoking method on this object
System.out.println("some other object name is: "+d.getName());// invoking method on some other object
}
//test
public static void main(String[] args) {
Demo d=new Demo("A");
Demo d2=new Demo("B");
d.test(d2);
}
}
output:
this object name is: A
some other object name is: B
public class TestClass{
public static void testStatic(){
System.out.println("test1");
}
public void testNonStatic(){
System.out.println("test2");
}
public void test1(){
// both is valid
testStatic();
TestClass.testStatic();
// this is valid, cause it can call the method of the same instance of that class
testNonStatic();
this.testNonStatic();
// this is not valid, cause without a concrete instance of a class you cannot call
// non static methods
TestClass.testNonStatic();
}
public static void test2(){
// again these are both correct
testStatic();
TestClass.testStatic();
// this doesn't work, cause you cannot call non static methods out of static methods
testNonStatic();
this.testNonStatic();
// this instead does work cause you have a concrete instance of the object
TestClass myTestClass = new TestClass();
myTestClass.testNonStatic();
// this still doesn't work
TestClass.testNonStatic();
}
}

Is there a way to access the variables of the calling class in a method?

At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
Example code:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}​
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.
Of course, the dirty little secret in Java is that reflection can get you around any private restriction.
But you should not resort to that. You should design your classes appropriately and respect the designs of others.
You can pass this as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}
you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance

Categories