0% found this document useful (0 votes)
5 views8 pages

Java Class Examples with Getters/Setters

java 4

Uploaded by

71762105014
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views8 pages

Java Class Examples with Getters/Setters

java 4

Uploaded by

71762105014
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name : Dhileep D

Class : Java test-3


Date: 10/1/2025

Source code: (private Setter,getter)

[Link] name,age,country
import [Link].*;
import [Link];

public class Person


{
private String name,country;
private int age=200;

public void setname(String name,int age,String country)


{
[Link]=name;
[Link]=age;
[Link]=country;
}
public String getname()
{
return name;
}
public int getAge()
{
return age;
}
public String getCountry()
{
return country;
}
public static void main(String args[])
{
Scanner obj=new Scanner([Link]);
Person classObj=new Person();
[Link]("Enter Person Name: ");
String name=[Link]();
[Link]("Enter "+name+"'s Age: ");
int age=[Link]();
[Link]();
[Link]("Enter "+name+"'s Country: ");
String Country=[Link]();

[Link](name,age,Country);
[Link]("");
[Link]("Person Details");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Output:

2 Bank Account

import [Link].*;

public class BankAccount


{
private String accountNumber="12345678910";
private Double balance=20000.50;

public void setAccountDetails(String accountNumber,Double balance)


{
[Link]=accountNumber;
[Link]=balance;
}
public String getaccountNo()
{
return accountNumber;
}
public Double getBalance()
{
return balance;
}
public static void main(String args[])
{
Scanner obj=new Scanner([Link]);
BankAccount classObj=new BankAccount();
[Link]("Default Account number: "+[Link]());
[Link]("Default Account Balance: "+[Link]());
[Link]("");
[Link]("Modifying Private Access!!! ");
[Link]("Enter Account Number :");
String Accountno=[Link]();
[Link]("Enter AccountBalance :");
Double Accountbalance=[Link]();
[Link](Accountno,Accountbalance);
[Link]("");
[Link]("Modified Private Access!!! ");
[Link]("Account number :"+ [Link]());
[Link]("Account number :"+ [Link]());
}
}
Output :
[Link]
import [Link].*;

public class Rectangle


{
private int length=200;
private int width=100;

public void setWidthLength(int width,int length)


{
[Link]=length;
[Link]=width;
}
public int getlength()
{
return length;
}
public int getwidth()
{
return width;
}
public static void main(String args[])
{
Scanner obj=new Scanner([Link]);
Rectangle classObj=new Rectangle();
[Link]("Default length: "+[Link]());
[Link]("Default Account Balance: "+[Link]());
[Link]("");
[Link]("Modifying Private Access!!! ");
[Link]("Enter Length :");
int length=[Link]();
[Link]("Enter width :");
int width=[Link]();
[Link](width,length);
[Link]("");
[Link]("Modified Private Access!!! ");
[Link]("length :"+ [Link]());
[Link]("width :"+ [Link]());
}
}
Output:

4) EmployeeSetGet
import [Link].*;

public class EmployeeSetGet


{
private String id="12345678910";
private String name="Manoj";
private Double salary=100000.30;
public void setEmployeeDetails(String id,String name,Double salary)
{
[Link]=id;
[Link]=name;
[Link]=salary;
}
public String getname(double salary)
{
return name;
}
public String getid(double salary)
{
return id;
}
public Double getsalary()
{
return salary;
}
public static void main(String args[])
{
Scanner obj=new Scanner([Link]);
EmployeeSetGet classObj=new EmployeeSetGet();
[Link]("Default Employee Id: "+[Link]([Link]()));
[Link]("Default Employee name: "+[Link]([Link]()));
[Link]("Default Employee salary: "+[Link]());
[Link]("");
[Link]("Modifying Private Access!!! ");
[Link]("Enter Employee Id :");
String id=[Link]();

[Link]("Enter Employee Name :");


String name=[Link]();
[Link]("Enter Employee salary :");
Double salary=[Link]();
[Link](id,name,salary);
[Link]("");
[Link]("Modified Private Access!!! ");
[Link]("Employee Id :"+ [Link](salary));
[Link]("Employee Name :"+ [Link](salary));
}
}
Output :

5. Circle

import [Link].*;

public class Circle


{
private int radius=30;

public void setradius(int r)


{
[Link]=r;
}
public int getradius()
{
return radius;
}
public Double area()
{
Double area=[Link]*radius*radius;
return area;
}
public Double perimeter()
{
Double perimeter=2*[Link]*radius;
return perimeter;
}

public static void main(String args[])


{
Scanner obj=new Scanner([Link]);
Circle classObj=new Circle();

[Link]("Default Radius Value : "+[Link]());


[Link]("");
[Link]("Modifying Private Access!!! ");
[Link]("Enter radius value :");
int radius=[Link]();
[Link](radius);
[Link]("");
[Link]("Modified Private Access!!! ");
[Link]("Radius value "+ [Link]());
[Link]("Area= "+[Link]());
[Link]("perimeter= "+[Link]());
}
}
Output :

Common questions

Powered by AI

The `Person` class in the Java program encapsulates its attributes by using private access modifiers for its fields: `name`, `age`, and `country`. This encapsulation restricts direct access to these attributes from outside the class, requiring the use of public methods (`setname`, `getname`, `getAge`, and `getCountry`) to access and modify the values. This approach enhances data protection by preventing unauthorized access or modification from outside the class, ensuring that any changes to the data must adhere to the logic defined within these methods .

The `setradius` and `getradius` methods in the `Circle` class ensure correctness by encapsulating the radius modification and access operations within controlled interfaces. The `setradius` method could incorporate input validation to prevent setting nonsensical or illegal radius values, such as negative numbers. Although the document doesn't explicitly show validation, encapsulating these operations allows for easy implementation of such checks. The `getradius` method provides a read-only operation, ensuring the current radius can be retrieved without modification, preventing common errors such as unintended changes to object state .

The default values set within these Java classes, such as a default radius of 30 in `Circle`, represent initial assumptions about the object's state. Limitations could arise when these defaults do not align with expected or valid ranges of operations in context-specific applications, potentially leading to logic errors or incorrect assumptions. The pros of initializing objects this way include ease of setup and reduced necessity for immediate user input; they ensure the object is in a consistent state immediately post-instantiation. However, cons include reduced flexibility and potential mismatch with specific operational needs, necessitating a careful balance between convenience and adaptability .

Removing encapsulation in the `Circle` class by making the `radius` field public would allow direct modification and access to this field. This change could lead to uncontrolled manipulation of `radius`, potentially resulting in incorrect calculations for the area and perimeter. Encapsulation ensures that any changes to `radius` would go through predefined methods, allowing for validation or constraints (e.g., non-negative radii), which would maintain the correctness of the calculations. Without encapsulation, there is increased risk of logic errors and inconsistency in the internal state of the object .

The code examples illustrate the use of Java's Scanner class to facilitate user interaction in console applications by reading input data from the console. In each class, a Scanner object is created to capture user input for modifying object state, such as changing dimensions in `Rectangle`, or personal information in `Person`. This directly engages users in setting or updating attribute values, enabling dynamic data entry and reflecting real-time changes in object state. The Scanner plays a critical role in enhancing interactivity, making console applications more responsive to user requirements and adaptable to various inputs .

Getter and setter methods in the `BankAccount` class provide controlled access to the private fields `accountNumber` and `balance`. The getter methods (`getaccountNo` and `getBalance`) enable reading the values of these fields, while the setter method (`setAccountDetails`) allows updating them. This supports object-oriented principles by maintaining encapsulation, as it allows for data hiding and the implementation of validation or logic within these methods before modifying the actual data .

Directly modifying private fields, if allowed, would compromise the design's integrity by bypassing the encapsulation barrier, which prevents unauthorized access and modification. It would undermine the controlled interaction setup via getters and setters, which can include validation, constraints, or additional processing logic necessary to maintain data consistency and correctness. This lack of control could lead to security vulnerabilities, such as inconsistent or unchecked inputs, buffer overflows, or exposure of critical data, ultimately weakening the software's robustness and reliability .

The `Rectangle` class can dynamically modify its dimensions using the `setWidthLength` method, which changes the private fields `length` and `width`. This process demonstrates object mutability as it allows instances of the class to change state by altering the dimensions after the object has been created. This flexibility is crucial in programming scenarios where an object's attributes need to adapt to varying inputs or conditions. The dynamic modification helps illustrate the difference between mutable and immutable objects, providing insight into how and when to apply these concepts .

The `EmployeeSetGet` class has potential for error due to the inappropriate use of overloading with its getter methods, such as `getname(double salary)` and `getid(double salary)`, which take a salary as a parameter unnecessarily. This could lead to misconceptions about the methods' purpose and introduces a point of failure if not properly handled. To improve robustness, these methods should be redefined without parameters, as the parameters do not influence the outcome. Additionally, validation checks could be added in the setter method to ensure that the salary is a non-negative value .

The Java code illustrates the basic principles of object-oriented programming (OOP) through encapsulation, polymorphism, abstraction, and inheritance (though inheritance is implied and not explicitly used in fragments). Encapsulation is demonstrated by using private fields and public getter/setter methods to protect the state of an object. Polymorphism is suggested by method overloading, albeit with design issues. Abstraction is seen in how the methods provide a simplified interface for complexity hidden internally. These OOP principles enhance software maintenance by promoting code reusability, reducing redundancy, and facilitating easier debugging and future development .

You might also like