Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementary Java/OOP uncertainties on fields and instances of a class

Tags:

java

In a class, you can create fields within them, as int bar in the following example.

Class foo{
    int bar;
    foo(int bar){
         bar = bar;
    }

    int getBar() {
         return bar;
    }   

    void setBar(int bar) {
         bar = bar;
    }
}
  1. Every time I create a new foo object in another class, will that particular object (instance of foo) have a bar property that when changed with the setBar(), only impacts that instance and no other instances?

  2. I often see people create getters and setters for properties like bar in the above example. If I feel lazy and I'm just writing code for myself/fun, can I just modify the bar property of any instance of this class by accessing the property FooInstance1.bar = 22; instead of having to write a setter and it will have the same effect as in question 1 (just the instance is changed)?

  3. How does the Java compiler know what method is a constructor? By the fact that it has the same name as the class? Or by the fact that one does not specify a return value in the function header? Perhaps it doesn't even matter what the compiler thinks is a constructor (no syntactic difference between regular function), it could be just a semantic thing that people use to differentiate the meaning of functions.

EDIT: I'm having a hard time selecting a best answer. I learned something new from everyone. Thanks!

like image 683
Wuschelbeutel Kartoffelhuhn Avatar asked Jan 23 '26 11:01

Wuschelbeutel Kartoffelhuhn


2 Answers

1) Yes. That's correct.

2) Yes you can, but the best practice is to use the getter and setter. That way, the author of the class can write special logic for the property that is assured to be executed on the get or set. For example, some properties may be calculated on the fly or a notification is sent to listeners when a property is changed.

3) The constructor is the method with no return value and which has the same name as the class. There can be any number of constructors, but each has to have a unique combination of argument types.

like image 83
Chris Gerken Avatar answered Jan 25 '26 01:01

Chris Gerken


  1. Yes, that is the behavior of member variables, one copy exists for each instance. static variables, on the other hand, are class-level variables, one copy shared by all instances.

  2. It is a good practice to not expose the members directly and provide getters to access them. Public setters are also generally discouraged to have better control on how the object state gets modified. But, yes, you can modify them directly also once you declare them as public.

  3. Yes, constructors are special methods without a return type and the name same as that of the class.

like image 27
Vikdor Avatar answered Jan 24 '26 23:01

Vikdor