Encapsulation Send
Encapsulation Send
1. Encapsulation Overview:
o Encapsulation is the aggregation of data and behavior.
o A class is a combination of data (fields/properties) and methods.
o Data should be hidden from the outside, and behaviors should be accessed only
via methods.
o Methods should include boundary conditions to ensure data validity.
o Constructors initialize objects, and getters/setters are used to enforce
encapsulation.
2. Identifying Classes:
o Main nouns represent classes.
o Nouns as modifiers of the main noun represent fields.
o Verbs related to the main noun represent methods.
o Example: For a student, the main noun is "Student," fields are code, name, birth
year, address, and methods are input and output.
3. Class Design Hints:
o Coupling: Low coupling is preferred to ensure that a class does not depend too
heavily on the internals of another class.
o Cohesion: High cohesion is preferred, where a class or method performs a single
task or closely related tasks.
4. Declaring/Using a Class in Java:
o Class declaration syntax is provided, including fields, constructors, and methods.
o Constructors can be default (no parameters) or parametric (with parameters).
5. Member Functions:
o Getter and Setter methods are used to read and modify field values while
maintaining encapsulation.
o Other methods include operations related to the class.
6. Creating Objects:
o Objects are created using the new keyword, which involves declaration,
instantiation, and initialization.
7. Access Modifiers:
o Access modifiers (public, protected, private, and default) control the visibility and
access levels of classes, methods, and fields.
8. Case Study:
o An example case study of a sports car is provided, demonstrating the application
of encapsulation principles in designing a class with various attributes and
methods.
1
Questions and Anwsers
2
java
Copy code
public class ClassName {
[modifier] Type field;
[modifier] Type method(Type param) {
// <code>
}
}
java
Copy code
public ClassName() {
// <initialization code>
}
java
Copy code
public ClassName(Type param1, Type param2) {
this.field1 = param1;
this.field2 = param2;
}
java
Copy code
public String getName() {
return name;
}
java
Copy code
public void setName(String name) {
if (!name.isEmpty()) {
this.name = name;
}
}
3
19. Q: How are arguments passed to a constructor or method in Java?
o A: Arguments are passed by value in Java, meaning that a copy of the argument is
passed to the method or constructor.
20. Q: How do you create an object of a class in Java?
o A:
java
Copy code
ClassName obj = new ClassName();
// or
ClassName obj = new ClassName(params);