简体   繁体   中英

Getting access to class properties from within class methods - Java

I have the following code:

public class UserRepository 
{       
    private MyDataSource myDataSource = new MyDataSource();

    public static User CreateUser( int id, String firstName, String lastName )
    {
         myDataSource.propertyOfThis...
         // myDataSource is not accessible and yet i have declared it as a property of UserRespository?
    }
...

What am i missing here?

myDataSource is not static

private MyDataSource myDataSource = new MyDataSource();

But CreateUser is static

public static User CreateUser( int id, String firstName, String lastName )

So make myDataSource static or remove CreateUser 's static modifier.

Oh, or a new UserRepository() .

You need to make myDataSource as static. Static method can be called without creating an instance and as myDataSource is an instance variable hence it is not accessible.

您的方法CreateUser是静态的,而MyDataSource是实例字段

The problem is that your field is not static , and yet you are using it in a static method.

The problem is that static methods are not executed on an instance of a class (object), but on the class itself. A field exists only in an object. Hence the method needs not to be static, or field should be static. Depends on your use case.

You method is static . As has been stated already, you cannot access non-static methods or variables from within a static method.

The reason for this is that static members and methods are accessible without the class being instantiated. However, those non-static (aka "instance") variables belong to a particular INSTANCE of that class. Therefore you have to have an instantiated object to reference in order to get the variables.

If you are in a static block of code, then you cannot use the keyword this for the same reason. this refers to a particular instantiated object of that class.

* The problem is that your field is not static, and yet you are using it in a static method. *The problem is that static methods are not executed on an instance of a class (object), but on the class itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM