why is it that importing java.awt.* doesn't also import java.awt.geom.*? Isn't everything within java.awt.geom inside of java.awt? I would assume so, judging by the name of the package.
The name of the packages are misleading. They are given names like java.awt
and java.awt.geom
, but those are actually entirely different packages. In Java there isn't really a "package hierarchy."
import java.awt.*;
imports all of the classes inside the java.awt
package. Because java.awt.geom
is a different package with different classes, you have to import that package too. The hierarchical names are mostly for organization!
accessing the instance variables directly was bad and that I should use the accessor method instead. Why is that? Is it just convention?
What Sotirios Delimanolis said about encapsulation was good, but I believe the best explanation is that in Object-Oriented Programming, you-the-programmer are responsible for deciding what a user (or a programmer using your package) is allowed to do with a class's member variables.
That's why it's convention to make member variables private
; the data stored in the object is the objet's responsibility, and it's your job as a programmer to make sure that interfacing with that object through the methods you define work properly. So if you want someone to be allowed to change the data in an object directly, you can make a set
method to do so.
Consider something like this:
Pizza myPizza = new Pizza(18) //18-inch pizza. Yum!
When I do this, the pizza will calculate other variable members such as numSlices
(currently 1, since it's uncut) and pizzaLeft
(which is (18/2)^2 * pi inches). Which of these makes more sense?
myPizza.pizzaLeft -= 50; //50 inches of pizza eaten
myPizza.pizzaLeft; //returns about 204.47
or
myPizza.slice(8); // cut into 8 pieces which are about 32 square inches each
myPizza.eat(1); // eat one slice
myPizza.getPizzaLeft(); //returns about 222.47
Since you're dealing with a pizza, it makes more sense to just cut into slices and eat pieces. The pizza object itself will be responsible for calculating the changes in things like pizzaLeft
or something like slicesLeft
, and those interfacing with the class don't see it.
It's because of THIS reason that member variables are conventionally set to private
, which then means that you have to use an accessor method.
I hope this helps.