Search code examples
javagetter

Call get method inside a method of a class


I'm just learning Java a bit. I have a simple question. I have 2 getter methods. Does my code have any problems if I call get method inside a non-static in a class like below? In addition, can getter method is set static. If it does, when it does. This code is just a sample code to post here.

public float testAverage(){
    float aver;
    
    aver = getTest1() + getTest2();
    
    return aver;}

Solution

  • Getter and Setters are used to encapsulate instance variables.

    When you make a method static it won't have access to instance variables, but only other static methods/variables within the class. Statics are used for instance-agnostic logic. As such you can only have static getter/setter methods for only static class variables.

    I have 2 getter methods. Does my code have any problems if I call get method inside a non-static in a class like below

    As long as getTest1 and getTest2 are none static then you will have access to them in other none-static methods.