Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Java public vs private, and the relationship between an event and listener.

zyzz28

Coder
Q1) Explain why it would be a poor decision to make instance data public instead of private. Give an example of why this could result in a problem.


Q2) Explain the relationship between an event and a listener.
 
1) conceptually a class represents the behaviour of something. An instance of a class is an object. Objects typically represent state, and the methods for an object typically control and ensure the object's integrity (correctness). To set the state of an object you usually call a function defined for that object with a new value, and the function would ensure that the value is correct, also ensuring the state of the object is correct.

Example: you have a class Calendar, which would represent a calendar. One possible value that a Calendar object could store is the current month, which would be represented as an integer value between 1 and 12 (there are other ways to represent this, but let's just roll with this example). If the member variable were public, allowing external users of the object write access, it would be possible to set this variable to an invalid value, whereas if it were private and accessed with getter/setter functions int getMonth()/void setMonth(int month), the function implementation would ensure that only correct values would be set for the month. You could potentially write code in calling functions to ensure that the value being written to the month variable in the calendar is valid, but this would lead to repetition and duplication of code which is considered bad design.

2) best to look at this from a GUI perspective example: mouse actions. Possible mouse actions example: mouse click. Your program can be written in such a way to listen for mouse clicks: the action of performing a mouse click raises an event. A listener is a class/function that would run based on events that it receives.
 

New Threads

Buy us a coffee!

Back
Top Bottom