0% found this document useful (0 votes)
39 views22 pages

Cons Get Set

constructer getter and setter java

Uploaded by

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

Cons Get Set

constructer getter and setter java

Uploaded by

6ahra Sad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Here are the definitions of class, object, argument, and attributes in Java, with simple

explanations:

1. Class:

A class is a blueprint for creating objects. It defines a set of properties (attributes) and behaviors
(methods) that the objects created from it will have. Think of a class as a template. In Java,
everything starts with a class.

Example:

class Car {

// Attributes

String color;

String model;

// Constructor (a special method to create objects)

public Car(String color, String model) {

this.color = color;

this.model = model;

// Method

public void displayInfo() {

System.out.println("Car Model: " + model + ", Color: " + color);

2. Object:
An object is an instance of a class. Once you create a class, you can create objects from it. Each
object has its own values for the properties defined by the class, but it follows the structure and
behavior specified by the class.

Example:

public class Main {

public static void main(String[] args) {

// Creating an object of the class Car

Car myCar = new Car("Red", "Toyota");

myCar.displayInfo(); // Output: Car Model: Toyota, Color: Red

Here, myCar is an object of the Car class.

3. Attribute:

Attributes (or fields) are variables that represent the properties of an object. These attributes are
defined within a class. Each object created from the class will have its own set of attribute values.

Example

class Person {

// Attributes

String name;

int age;

// Constructor

public Person(String name, int age) {

this.name = name; // 'name' is an attribute

this.age = age; // 'age' is an attribute

}
In this example, name and age are attributes of the Person class.

4. Argument:

An argument is a value you pass into a method or constructor when you call it. These arguments
are used by the method or constructor to perform actions. They are also known as parameters.

Example:

class Calculator {

// Method with two arguments

public int add(int a, int b) {

return a + b;

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

int sum = calc.add(10, 20); // Passing arguments 10 and 20

System.out.println("Sum: " + sum); // Output: Sum: 30

Here, 10 and 20 are arguments passed to the add method of the Calculator class.

Summary:

 A class defines the blueprint or structure for objects.


 An object is an instance of a class with specific values for its attributes.
 Attributes (or fields) are variables inside a class that define properties of an object.
 Arguments are the values passed to methods or constructors when they are called.
Constructors, Getters, and Setters in Java

1. Constructors in Java

A constructor in Java is a special type of method that is used to initialize objects. The
constructor is called when an object of a class is created. It has the same name as the class and
does not return any value (not even void).

Types of Constructors

 Default Constructor: Provided by the compiler if no constructor is defined by the user.


 Parameterized Constructor: A constructor that takes arguments to set initial values for
object attributes.

Syntax of a Constructor

class ClassName {

// Constructor

ClassName() {

// Code to initialize the object

// Parameterized constructor

ClassName(String name, int age) {

this.name = name;

this.age = age;

}
Example of Constructor:

class Person {

String name;

int age;

// Default constructor

Person() {

this.name = "Unknown";

this.age = 0;

// Parameterized constructor

Person(String name, int age) {

this.name = name;

this.age = age;

void displayInfo() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

public class Main {

public static void main(String[] args) {

Person person1 = new Person(); // Calls default constructor

Person person2 = new Person("John", 25); // Calls parameterized constructor

person1.displayInfo();

person2.displayInfo();
}

Use Case of Constructors:

Constructors are used to initialize object state when an object is created. For example, if you
create a Car class, the constructor can initialize the car’s brand, model, and year when a Car
object is created.

2. Getters and Setters

In Java, getters and setters are methods used to access and update private variables of a class.
These methods are part of the Encapsulation principle in object-oriented programming, where
data is hidden and controlled through accessors.

Why Use Getters and Setters?

 Encapsulation: To hide the implementation details of a class and only expose safe access
through methods.
 Control Over Data: Getters and setters allow you to control how variables are accessed
and updated (e.g., by adding validation).

Getter Method: A getter method returns the value of a private variable. It is usually prefixed with the word
get.

Setter Method: A setter method sets or updates the value of a private variable. It is usually prefixed with the
word set.
Syntax of Getters and Setters

class ClassName {

// Private variables

private String name;

private int age;

// Getter for name

public String getName() {

return name;

// Setter for name

public void setName(String name) {

this.name = name;

// Getter for age

public int getAge() {

return age;

// Setter for age

public void setAge(int age) {

this.age = age;

}
Example of Getters and Setters:

class Person {

// Private attributes

private String name;

private int age;

// Constructor

Person(String name, int age) {

this.name = name;

this.age = age;

// Getter for name

public String getName() {

return name;

// Setter for name

public void setName(String name) {

this.name = name;

// Getter for age

public int getAge() {

return age;

}
// Setter for age

public void setAge(int age) {

if (age > 0) {

this.age = age;

} else {

System.out.println("Age must be positive.");

// Method to display information

public void displayInfo() {

System.out.println("Name: " + getName());

System.out.println("Age: " + getAge());

public class Main {

public static void main(String[] args) {

// Creating a person object using the constructor

Person person = new Person("Alice", 30);

// Using getter and setter methods

person.setName("Bob");

person.setAge(25);

// Display updated information


person.displayInfo();

Use Case of Getters and Setters:

Imagine a scenario where you want to ensure that the age of a person cannot be set to a negative
number. Using a setter, you can validate the input before updating the value of the age attribute.
Similarly, getters allow controlled access to private fields, preventing direct access to class
members from outside.

Key Benefits of Getters and Setters:

 Encapsulation: Hide the class data and provide controlled access.


 Data Validation: In setters, you can validate or modify the input before setting it (e.g.,
ensuring the age is positive).
 Flexibility: You can modify the internal implementation without affecting how external
classes access your class's data.

Summary

 Constructors initialize the state of objects when they are created.


 Getters allow controlled access to private class members.
 Setters allow controlled modification of private class members, often with data
validation.

Here's a simple exercise on constructors, getters, and setters for you to practice.

Exercise: Creating a "Car" Class

Objective: Create a Car class that stores the following attributes:

 brand: A string representing the car's brand.


 model: A string representing the car's model.
 year: An integer representing the year the car was made.

Requirements:

1. Use private access modifiers for all attributes.


2. Create a constructor to initialize the brand, model, and year attributes.
3. Implement getters and setters for each attribute:
o The getYear() method should return the year.
o The setYear() method should only allow values greater than 1886 (the year the
first car was invented).
4. Write a displayCarInfo() method that prints the car’s information to the console.

Solution

Here's a possible solution with the constructor, getters, and setters:

java
Copy code
class Car {
// Private attributes
private String brand;
private String model;
private int year;

// Constructor to initialize the car object


public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.setYear(year); // Use the setter to enforce validation
}

// Getter for brand


public String getBrand() {
return brand;
}

// Setter for brand


public void setBrand(String brand) {
this.brand = brand;
}

// Getter for model


public String getModel() {
return model;
}

// Setter for model


public void setModel(String model) {
this.model = model;
}

// Getter for year


public int getYear() {
return year;
}

// Setter for year (with validation)


public void setYear(int year) {
if (year > 1886) {
this.year = year;
} else {
System.out.println("Year must be greater than 1886.");
}
}

// Method to display car information


public void displayCarInfo() {
System.out.println("Car Brand: " + brand);
System.out.println("Car Model: " + model);
System.out.println("Car Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
// Create a Car object using the constructor
Car myCar = new Car("Toyota", "Corolla", 2020);

// Display initial car info


myCar.displayCarInfo();

// Update the car model and year using setters


myCar.setModel("Camry");
myCar.setYear(2018);

// Display updated car info


System.out.println("\nUpdated Car Info:");
myCar.displayCarInfo();
}
}

Explanation:

 The Car class has private attributes: brand, model, and year.
 The constructor takes three arguments to initialize these attributes.
 Getter and setter methods are created for each attribute to provide controlled access.
 The setYear() method ensures that only valid years (greater than 1886) are allowed.
 The displayCarInfo() method prints out the car’s details.

Next Steps for Practice:

1. Test different cases: Create another Car object and try setting invalid years (like 1700) to
check if the validation works.
2. Modify the class: Add more attributes like color or price, and include them in the
constructor, getters, and setters.
3. Experiment: Try creating getter and setter methods with additional logic, like formatting
the model name or setting a maximum year limit.
Exercise 1: "Student" Class

Objective: Create a Student class with the following attributes:

 name (String)
 age (int)
 gpa (double)

Requirements:

1. The gpa should be between 0.0 and 4.0.


2. Implement a constructor to initialize the student’s name, age, and gpa.
3. Create getters and setters for each attribute.
4. The setter for gpa should ensure the value is within the allowed range (0.0 to 4.0).
5. Write a displayInfo() method that prints the student's details.

Exercise 2: "BankAccount" Class

Objective: Create a BankAccount class with the following attributes:

 accountNumber (String)
 balance (double)

Requirements:

1. Implement a constructor to initialize the account with an account number and an initial
balance.
2. Implement getter and setter methods for the balance.
3. Ensure that the balance cannot be negative (i.e., add a check in the setter).
4. Implement a method deposit(double amount) to add money to the account.
5. Implement a method withdraw(double amount) to remove money, but only if the
balance is sufficient.

Exercise 3: "Rectangle" Class

Objective: Create a Rectangle class with the following attributes:

 length (double)
 width (double)

Requirements:
1. Create a constructor to initialize the rectangle with length and width.
2. Add getters and setters for both attributes. Ensure that the length and width cannot be
negative.
3. Implement a method calculateArea() that returns the area of the rectangle.
4. Implement a method calculatePerimeter() that returns the perimeter of the rectangle.

Exercise 4: "Book" Class

Objective: Create a Book class with the following attributes:

 title (String)
 author (String)
 price (double)

Requirements:

1. Create a constructor that takes all three attributes as arguments.


2. Implement getter and setter methods for each attribute.
3. The setter for price should not allow a negative value.
4. Add a method displayBookInfo() that prints the book's information.
5. Write a method applyDiscount(double percentage) that reduces the price of the book
by the given percentage.

Exercise 5: "Employee" Class

Objective: Create an Employee class with the following attributes:

 name (String)
 position (String)
 salary (double)

Requirements:

1. Create a constructor to initialize the name, position, and salary.


2. Implement getters and setters for each attribute.
3. Ensure that the salary cannot be negative.
4. Add a method promote(String newPosition, double salaryIncrease) that changes
the position and increases the salary.
5. Write a method displayEmployeeDetails() to print the employee’s details.
Exercise 6: "Circle" Class

Objective: Create a Circle class with the following attribute:

 radius (double)

Requirements:

1. Create a constructor that initializes the circle’s radius.


2. Implement getter and setter methods for the radius. Ensure that the radius is always
positive.
3. Add a method calculateArea() that returns the area of the circle.
4. Add a method calculateCircumference() that returns the circumference of the circle.

Exercise 7: "Library" Class

Objective: Create a Library class with the following attributes:

 name (String)
 location (String)
 numberOfBooks (int)

Requirements:

1. Create a constructor that initializes the name, location, and numberOfBooks.


2. Implement getters and setters for each attribute.
3. Add a method addBooks(int books) to increase the number of books in the library.
4. Write a method lendBook() that decreases the number of books by 1 if there are books
available.
5. Implement a method displayLibraryInfo() that prints the library’s details.

Exercise 8: "Movie" Class

Objective: Create a Movie class with the following attributes:

 title (String)
 director (String)
 rating (double)

Requirements:

1. Create a constructor to initialize all the attributes.


2. Implement getters and setters for each attribute.
3. The setter for rating should ensure the rating is between 0.0 and 10.0.
4. Add a method displayMovieDetails() to print the movie’s details.

Exercise 9: "StudentGrades" Class

Objective: Create a StudentGrades class with the following attributes:

 studentName (String)
 subject (String)
 grade (double)

Requirements:

1. Create a constructor to initialize the attributes.


2. Implement getters and setters for each attribute.
3. Ensure the grade is between 0.0 and 100.0 using the setter.
4. Add a method isPassing() that returns true if the grade is above 60, otherwise returns
false.
5. Add a method displayStudentGrade() to print the student’s details and grade.

Exercise 10: "TemperatureConverter" Class

Objective: Create a TemperatureConverter class with a single attribute:

 celsius (double)

Requirements:

1. Create a constructor to initialize the celsius value.


2. Add a getter and setter for celsius.
3. Add a method convertToFahrenheit() that converts the Celsius temperature to
Fahrenheit using the formula: F = C * 9/5 + 32.
4. Add a method convertToKelvin() that converts Celsius to Kelvin using the formula: K
= C + 273.15.
5. Add a method displayTemperature() that prints the temperature in Celsius, Fahrenheit,
and Kelvin.

6. Here are the solutions for the exercises, with explanations provided for each.
7.
Solution 1: "Student" Class
8. java
9. Copy code
10. class Student {
11. // Private attributes
12. private String name;
13. private int age;
14. private double gpa;
15.
16. // Constructor
17. public Student(String name, int age, double gpa) {
18. this.name = name;
19. this.age = age;
20. this.setGpa(gpa); // Use the setter to ensure GPA validation
21. }
22.
23. // Getter for name
24. public String getName() {
25. return name;
26. }
27.
28. // Setter for name
29. public void setName(String name) {
30. this.name = name;
31. }
32.
33. // Getter for age
34. public int getAge() {
35. return age;
36. }
37.
38. // Setter for age
39. public void setAge(int age) {
40. this.age = age;
41. }
42.
43. // Getter for GPA
44. public double getGpa() {
45. return gpa;
46. }
47.
48. // Setter for GPA with validation
49. public void setGpa(double gpa) {
50. if (gpa >= 0.0 && gpa <= 4.0) {
51. this.gpa = gpa;
52. } else {
53. System.out.println("Invalid GPA. It must be between 0.0
and 4.0.");
54. }
55. }
56.
57. // Method to display student information
58. public void displayInfo() {
59. System.out.println("Student Name: " + name);
60. System.out.println("Age: " + age);
61. System.out.println("GPA: " + gpa);
62. }
63. }

Solution 2: "BankAccount" Class


64. java
65. Copy code
66. class BankAccount {
67. // Private attributes
68. private String accountNumber;
69. private double balance;
70.
71. // Constructor
72. public BankAccount(String accountNumber, double initialBalance) {
73. this.accountNumber = accountNumber;
74. this.setBalance(initialBalance); // Use setter to ensure valid
balance
75. }
76.
77. // Getter for accountNumber
78. public String getAccountNumber() {
79. return accountNumber;
80. }
81.
82. // Getter for balance
83. public double getBalance() {
84. return balance;
85. }
86.
87. // Setter for balance with validation
88. public void setBalance(double balance) {
89. if (balance >= 0) {
90. this.balance = balance;
91. } else {
92. System.out.println("Balance cannot be negative.");
93. }
94. }
95.
96. // Method to deposit money
97. public void deposit(double amount) {
98. if (amount > 0) {
99. balance += amount;
100. System.out.println("Deposited: " + amount);
101. } else {
102. System.out.println("Deposit amount must be positive.");
103. }
104. }
105.
106. // Method to withdraw money
107. public void withdraw(double amount) {
108. if (amount > 0 && balance >= amount) {
109. balance -= amount;
110. System.out.println("Withdrew: " + amount);
111. } else {
112. System.out.println("Insufficient balance or invalid
amount.");
113. }
114. }
115.
116. // Method to display account information
117. public void displayAccountInfo() {
118. System.out.println("Account Number: " + accountNumber);
119. System.out.println("Balance: " + balance);
120. }
121. }

Solution 3: "Rectangle" Class


122. java
123. Copy code
124. class Rectangle {
125. // Private attributes
126. private double length;
127. private double width;
128.
129. // Constructor
130. public Rectangle(double length, double width) {
131. this.setLength(length);
132. this.setWidth(width);
133. }
134.
135. // Getter for length
136. public double getLength() {
137. return length;
138. }
139.
140. // Setter for length with validation
141. public void setLength(double length) {
142. if (length > 0) {
143. this.length = length;
144. } else {
145. System.out.println("Length must be positive.");
146. }
147. }
148.
149. // Getter for width
150. public double getWidth() {
151. return width;
152. }
153.
154. // Setter for width with validation
155. public void setWidth(double width) {
156. if (width > 0) {
157. this.width = width;
158. } else {
159. System.out.println("Width must be positive.");
160. }
161. }
162.
163. // Method to calculate area
164. public double calculateArea() {
165. return length * width;
166. }
167.
168. // Method to calculate perimeter
169. public double calculatePerimeter() {
170. return 2 * (length + width);
171. }
172.
173. // Method to display rectangle information
174. public void displayRectangleInfo() {
175. System.out.println("Length: " + length);
176. System.out.println("Width: " + width);
177. System.out.println("Area: " + calculateArea());
178. System.out.println("Perimeter: " + calculatePerimeter());
179. }
180. }

Solution 4: "Book" Class

181. java
182. Copy code
183. class Book {
184. // Private attributes
185. private String title;
186. private String author;
187. private double price;
188.
189. // Constructor
190. public Book(String title, String author, double price) {
191. this.title = title;
192. this.author = author;
193. this.setPrice(price); // Use setter to ensure valid price
194. }
195.
196. // Getter for title
197. public String getTitle() {
198. return title;
199. }
200.
201. // Setter for title
202. public void setTitle(String title) {
203. this.title = title;
204. }
205.
206. // Getter for author
207. public String getAuthor() {
208. return author;
209. }
210.
211. // Setter for author
212. public void setAuthor(String author) {
213. this.author = author;
214. }
215.
216. // Getter for price
217. public double getPrice() {
218. return price;
219. }
220.
221. // Setter for price with validation
222. public void setPrice(double price) {
223. if (price >= 0) {
224. this.price = price;
225. } else {
226. System.out.println("Price cannot be negative.");
227. }
228. }
229.
230. // Method to display book information
231. public void displayBookInfo() {
232. System.out.println("Title: " + title);
233. System.out.println("Author: " + author);
234. System.out.println("Price: $" + price);
235. }
236.
237. // Method to apply discount
238. public void applyDiscount(double percentage) {
239. if (percentage > 0 && percentage <= 100) {
240. price = price - (price * percentage / 100);
241. System.out.println("Discount applied. New price: $" +
price);
242. } else {
243. System.out.println("Invalid discount percentage.");
244. }
245. }
246. }

Solution 5: "Employee" Class


247. java
248. Copy code
249. class Employee {
250. // Private attributes
251. private String name;
252. private String position;
253. private double salary;
254.
255. // Constructor
256. public Employee(String name, String position, double salary) {
257. this.name = name;
258. this.position = position;
259. this.setSalary(salary); // Use setter to ensure valid salary
260. }
261.
262. // Getter for name
263. public String getName() {
264. return name;
265. }
266.
267. // Setter for name
268. public void setName(String name) {
269. this.name = name;
270. }
271.
272. // Getter for position
273. public String getPosition() {
274. return position;
275. }
276.
277. // Setter for position
278. public void setPosition(String position) {
279. this.position = position;
280. }
281.
282. // Getter for salary
283. public double getSalary() {
284. return salary;
285. }
286.
287. // Setter for salary with validation
288. public void setSalary(double salary) {
289. if (salary >= 0) {
290. this.salary = salary;
291. } else {
292. System.out.println("Salary cannot be negative.");
293. }
294. }
295.
296. // Method to promote employee
297. public void promote(String newPosition, double salaryIncrease) {
298. this.position = newPosition;
299. this.setSalary(this.salary + salaryIncrease); // Use setter
for validation
300. System.out.println(name + " has been promoted to " +
newPosition);
301. }
302.
303. // Method to display employee details
304. public void displayEmployeeDetails() {
305. System.out.println("Employee Name: " + name);
306. System.out.println("Position: " + position);
307. System.out.println("Salary: $" + salary);
308. }
309. }

You might also like