Cons Get Set
Cons Get Set
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;
this.color = color;
this.model = model;
// Method
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:
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
}
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 {
return a + b;
Here, 10 and 20 are arguments passed to the add method of the Calculator class.
Summary:
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
Syntax of a Constructor
class ClassName {
// Constructor
ClassName() {
// Parameterized constructor
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
this.name = name;
this.age = age;
void displayInfo() {
person1.displayInfo();
person2.displayInfo();
}
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.
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.
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
return name;
this.name = name;
return age;
this.age = age;
}
Example of Getters and Setters:
class Person {
// Private attributes
// Constructor
this.name = name;
this.age = age;
return name;
this.name = name;
return age;
}
// Setter for age
if (age > 0) {
this.age = age;
} else {
person.setName("Bob");
person.setAge(25);
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.
Summary
Here's a simple exercise on constructors, getters, and setters for you to practice.
Requirements:
Solution
java
Copy code
class Car {
// Private attributes
private String brand;
private String model;
private int year;
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.
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
name (String)
age (int)
gpa (double)
Requirements:
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.
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.
title (String)
author (String)
price (double)
Requirements:
name (String)
position (String)
salary (double)
Requirements:
radius (double)
Requirements:
name (String)
location (String)
numberOfBooks (int)
Requirements:
title (String)
director (String)
rating (double)
Requirements:
studentName (String)
subject (String)
grade (double)
Requirements:
celsius (double)
Requirements:
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. }
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. }