Defining Setters- Assigning Values to Attributes

Our Objective

To implement a program that defining setters assigning values to attributes. 


The Theory

Setters in Java are methods used to set the values of private instance variables (fields) in a class. They provide a way to encapsulate and control the assignment of values to the variables, allowing for data abstraction and maintaining the integrity of the object's state. 

This program consists of two classes: Point and Driver. 

  1. Point class: 
    1. Instance variables: 
      1. x (private int): Represents the x-coordinate of a point. 
      2. y (private int): Represents the y-coordinate of a point. 
    2. Methods: 
      1. setX(int xCoord): A private method that sets the value of the x-coordinate (x) to the provided xCoord parameter. 
      2. setY(int yCoord): A private method that sets the value of the y-coordinate (y) to the provided yCoord parameter. 
  2. Driver class: 
    1. Main method: 
      1. main(String[]): The entry point of the program. It creates an object P of the    Point  class and performs the following operations.
      2. Calls the 'setX()' method of the 'Point' class and sets the x-coordinate (x) to 2. 
      3. Calls the 'setY()' method of the 'Point' class and sets the y-coordinate (y) to 3. 


The program demonstrates the concept of encapsulation by encapsulating the 'x' and 'y' variables within the 'Point' class and providing controlled access to them through the private methods 'setX()' and 'setY()'. The 'Driver' class serves as an example of how to use the 'Point' class by creating an instance of it and setting the 'x' and 'y' coordinates using the provided methods. 

Class Diagram 

Sequence Diagram 

Learning Outcomes 

  • Encapsulation and data hiding: Understanding setters helps in grasping the concept of encapsulation, which is a fundamental principle in object-oriented programming. Setters allow you to hide the internal implementation details of a class and provide controlled access to attribute values, promoting data integrity and security. 
  • Access control and privacy: By using setters, you can control access to attribute values, ensuring that they are accessed only through defined methods. This helps in enforcing privacy and preventing unauthorized modification of attributes, thereby maintaining the integrity of the object's state. 
  • Consistent and intuitive interface: Setters provide a standardized way of accessing attribute values across different instances of a class. By using setters, you establish a consistent interface for interacting with objects, making the code more readable, maintainable, and intuitive for other developers.