Java Java Objects Meet Objects Methods

mohammed abdi abdulahi warsame
mohammed abdi abdulahi warsame
4,926 Points

General question

I didnt understand the part where the teacher is using PezDispenser Dispenser = new PezDispenser(); , what are we really trying to do? and whats new? what is the reason that we are trying to learn (get)? is it important? because i was folloing with the teacher and its kind hard to understand the main of this. and whay are we learning private and puplic? do we need it?

1 Answer

Katie Wood
Katie Wood
19,129 Points

Hi there,

It looks like you're on the section about objects - they let you create a sort of blueprint for a collection of methods and attributes that you might want to reuse. In the first examples, it might not be obvious why it's necessary, but they get really useful in more complicated programs.

Now, to your questions - when you make the code for a class, you aren't actually creating the object itself - just the blueprint for it. You create the actual object when you declare a 'new' one, which is happening there. The benefit of this is that you could create more than one if you wanted to - each of those would be an "instance" of that object.

Get methods and 'public'/'private' go hand-in-hand. Public and private helps you to determine the scope of your attributes and methods - scoping is a really important part of program design. If, for example, everything in an object is freely accessible from anywhere in the program, you could run into unexpected conflicts or behaviors as things get more complicated. Scoping allows you to control exactly how the class and its attributes can be affected by the rest of the program. Classes can also be reused in other applications and by other programmers - your scoping can help to communicate to others (or to yourself in the future) how the class is meant to be used. "Public" means it can be accessed from anywhere in the program, and "private" means it can only be accessed from within that object.

It's generally good practice to keep the actual attributes private, and provide public methods to access them. That's where your 'getters' and 'setters' come in - these are usually public methods that allow the retrieval or modification of a value. You can control how the attributes can be changed or viewed from outside the class through these methods. At the same time, you'll probably have other methods that are public or private depending on what they do.

I hope this helps!

Oziel Perez
Oziel Perez
61,321 Points

For those coming from a javascript background: remember how in some courses they say not to pollute the global scope/namespace with new variables? that's because we may accidentally assign new values that we didn't intend to and cause bugs, which is why they tell us to use 'closures' or try to define variables inside a function. Since there is no functions in Java, you use access modifiers instead.