6.3 Class Design
In this module, we will cover the essentials of class design, including fields, methods, constructors, and visibility modifiers. You will learn how to create well-structured Java classes with appropriate access control and understand object behavior.
- Class Structure and Members
- Method and Constructor Overloading
- Object Behavior and Memory Management
- Advanced Class Features
Learning Objectives:
- Learn how to design a class by adding fields, methods, and constructors.
- Understand how to control access to class members with visibility modifiers.
- Master method and constructor overloading techniques.
- Explore memory management concepts and advanced class features.
1. Class Structure and Members
Adding Fields with Types and Visibility Modifiers
Fields define the state of an object. They are variables that belong to a class and have types (such as int, String, etc.). Visibility modifiers such as private, protected, and public help in controlling how fields are accessed and modified.
Example:
public class Car {
private String model;
private int year;
}
Always use private for fields to encapsulate data and protect it from unwanted modification. Use public getter and setter methods to control access.
Declaring and Defining Methods with Parameters and Return Types
Methods define the behavior of an object. Each method has a return type, a name, and a list of parameters.
Example:
public int addNumbers(int a, int b) {
return a + b;
}
Always name methods clearly to reflect the action they perform. This improves code readability and maintainability.
Adding Constructors to Classes with Parameters
Constructors initialize objects. They have the same name as the class and no return type. Constructors can take parameters to set the initial state of an object when it's created.
Example:
public class Car {
private String model;
private int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
2. Method and Constructor Overloading
Overloading Methods and Constructors
Method overloading allows you to create multiple methods with the same name but different parameter lists. Similarly, constructor overloading allows objects to be initialized in different ways.
Example:
public int addNumbers(int a, int b) {
return a + b;
}
public double addNumbers(double a, double b) {
return a + b;
}
Method overloading improves flexibility by allowing you to use the same method name for different types or numbers of parameters.
Using Visibility Modifiers to Control Access to Class Members
Visibility modifiers control how fields and methods are accessed:
- public: Accessible by any class, regardless of package.
- private: Accessible only within the class itself, not visible to subclasses or other classes.
- protected: Accessible within the same package and by subclasses, even if they are in different packages.
- default (package-private): Accessible only within the same package; not visible to classes in other packages unless specified.
In Java, the default access modifier (also known as package-private) allows classes, methods, and fields to be accessible only within their own package. This means that if no access modifier is specified, the member is not accessible outside its package. To maintain encapsulation and data integrity, it’s recommended to minimize the use of public fields. Instead, use private fields with public getters and setters. This approach allows you to control how data is accessed and modified, ensuring that you can implement validation or other logic if needed.
Always minimize the use of public fields. Control access with getters and setters to maintain encapsulation and data integrity.
3. Object Behavior and Memory Management
Object Memory Layout in Java
In Java, objects are stored in memory in two main areas:
- Heap: Where objects are dynamically allocated.
- Stack: Where method calls and local variables are stored.
Understanding how memory works helps you avoid common pitfalls like memory leaks and stack overflows.
Working with Object References and the this Keyword
The this keyword refers to the current object instance. It is used when instance variables have the same name as method parameters to avoid confusion.
Example:
public class Person {
private String name;
public Person(String name) {
this.name = name; // 'this' refers to the instance variable
}
}
Comparing Object References
- The
==operator checks if two references point to the same object in memory. - The
.equals()method checks if two objects are logically equivalent.
Example:
Person p1 = new Person("Alice");
Person p2 = new Person("Alice");
System.out.println(p1 == p2); // false, different memory locations
System.out.println(p1.equals(p2)); // true, logical equality
4. Advanced Class Features
Adding Static Fields and Methods to Classes
Static fields and methods belong to the class itself rather than to individual instances. Static methods can be called without creating an instance of the class.
Example:
public class MathUtil {
public static int add(int a, int b) {
return a + b;
}
}
Use static methods when the method logic doesn't rely on instance variables and should be accessible at the class level.
Understanding Pass-by-Value vs. Pass-by-Reference
In Java, method arguments are always passed by value:
- For primitive types, the actual value is copied.
- For objects, the reference to the object is copied, but not the object itself.
Example:
public void modify(int num, Person person) {
num = 10; // The original value remains unchanged
person.setName("New Name"); // The object itself is modified
}
Live Demos: Visibility Modifiers and Passing by Value/Reference
Live coding demos will showcase how visibility modifiers protect data and how pass-by-value impacts method calls, especially with object references.
Module Wrap-Up
In this module, we've covered:
- Class structure, fields, and methods.
- Method and constructor overloading.
- Object behavior, memory management, and advanced class features such as static methods.
By mastering these concepts, you can design robust, maintainable, and well-structured Java applications.