I've just started learning Java, and am struggling to understand the (seemingly unnecessary) point of getters and setters.
I'm following a tutorial on Codecademy, and it has asked me to create the method getAge(). What is the point in creating a method to get the age, when I could just run the line I wrote and commented out below?
class Dog {
int age;
public Dog(int dogsAge) {
age = dogsAge;
}
public void bark() {
System.out.println("Woof!");
}
public void run(int feet){
System.out.println("Your dog ran " + feet + " feet!");
}
public int getAge() {
return age;
}
public static void main(String[] args) {
Dog spike = new Dog(1);
spike.bark();
spike.run(100);
int spikeAge = spike.getAge();
System.out.println(spikeAge);
//System.out.println(spike.age);
}
}
It seems like it would save a few lines of code. I'm sure I'm probably missing the point of OOP somewhere though?
Similarly with the age variable, why do I need to declare the age type, then create a method setting the age equal to another age variable? Could I just use this.age = age? To save writing extra code?