Aula 3 - Anatomy of A Class
Aula 3 - Anatomy of A Class
Lesson 3
The Anatomy of a Class and Revision
1
What is an Object?
2
Class vs. Object - Analogy
• Class (Blueprint):
• House plan
• Cookie cutter
• Car design
• Object (Instance):
• Actual house built from the plan
• A cookie made from the cutter
• A specific car built using the design
3
Class Components Summary
A class is composed of several key elements that define its structure and behavior:
• Name: A unique identifier for the class, reflecting its purpose and adhering to
language conventions.
• Comments/Docstrings: Explanatory text that documents the class’s functionality,
usage, and design decisions.
• Attributes (Fields/Properties): Variables that store the state of an object,
representing its data.
• Methods (Functions): Functions that define the behavior of the class, operating on
its attributes and performing actions.
• Constructors: Special methods used to initialize objects when they are created,
setting their initial state.
• Accessors (Getters/Setters): Methods that provide controlled access to the class’s
attributes, ensuring data integrity.
4
The Name of the Class
Importance of Class Names
• Identification: The name of the class is important to identify the class itself.
• Descriptiveness: Beyond simple identification, the name must be descriptive. It
provides information about what the class does and how it interacts within larger
systems.
• Language Constraints: The choice of a name is important considering language
constraints. For example, in Java, the public class name must be the same as the file
name. If the names do not match, the application won’t work.
p u b l i c c l a s s Cabbie {
}
6
Importance of Good Comments
• Maintainability: Comments explain the ”why” behind the code, making it easier to
understand and modify later.
• Collaboration: Comments facilitate teamwork by clarifying code intent for other
developers.
• Self-Documenting Code: Aim for code that is clear and readable without excessive
comments.
• Use meaningful variable and method names.
• Break down complex logic into smaller, well-named functions.
• When Comments Are Necessary:
• Explaining complex algorithms or logic.
• Documenting assumptions or design decisions.
• Providing context for non-obvious code.
• Generating API documentation (Javadoc).
7
Docstrings in Java (Javadoc)
8
Docstrings in Java (Javadoc)
/* *
* This class represents a simple calculator .
* @author John Doe
* @version 1.0
*/
public class Calculator {
/* *
* Adds two integers .
* @param a The first integer .
* @param b The second integer .
* @return The sum of a and b .
*/
public int add ( int a , int b ) {
return a + b ;
}
}
9
Attributes
Attributes in Object-Oriented Programming
Attributes represent the state of the object because they store the information about the
object. For our example, the Cabbie class has attributes that store the name of the
company, the name of the cabbie, and the cab assigned to the cabbie. For example, the
first attribute stores the name of the company:
private static S t r i n g companyName = ” B l u e Cab Company ” ;
Note here the two keywords private and static. The keyword private signifies that a
method or variable can be accessed only within the declaring object.
Hiding as Much Data as Possible
All the attributes in this example are private. This is in keeping with the design principle
of keeping the interface design as minimal as possible. The only way to access these
attributes is through the method interfaces provided (which we explore later in this
chapter).
10
User Attributes in Cabbie Class
Static Keyword: The static keyword signifies that there
will be only one copy of this attribute for all the objects
instantiated by this class. This is a class attribute.
private static S t r i n g companyName = ” B l u e Cab Company ” ;
• Importance of Initialization:
• Uninitialized primitive variables might have default values, but it’s best to be explicit.
• Uninitialized reference variables are null, leading to errors if used without checking.
• Explicit initialization improves code clarity and robustness. 12
Attribute Modifiers
• Access Modifiers:
• public: Attribute is accessible from any class.
• private: Attribute is accessible only within the declaring class.
• protected: Attribute is accessible within the declaring class and its subclasses.
• (default/package-private): Attribute is accessible within the same package.
• Other Modifiers:
• static: Attribute belongs to the class itself, not to instances of the class.
• final: Attribute’s value cannot be changed after initialization.
• transient: Attribute is not serialized.
• volatile: Attribute is always read from main memory.
13
Methods
Methods: Defining Behavior
• Methods define the behavior of a class. They represent actions that objects of the
class can perform.
• They operate on the object’s attributes and can interact with other objects.
• Methods can have parameters to receive input and return values as output.
• They encapsulate specific functionalities, promoting code reusability and modularity.
public class Calculator {
public int add ( int a , int b ) {
return a + b ;
}
public double divide ( double numerator , double denominator ) {
if ( denominator != 0) {
return numerator / denominator ;
} else {
System . out . println ( " Cannot divide by zero . " ) ;
return 0.0;
}
}
} 14
Messaging: Object Communication
15
Accessors
Accessor Methods and Data Integrity
// Set the Name of the Cabbie
public void setName ( String iName ) {
name = iName ;
}
// Get the Name of the Cabbie
public String getName () {
return name ;
}
In this code snippet, a Supervisor object must ask the Cabbie object
to return its name. It is good because you might have a setAge()
method that checks to see whether the age entered was 0 or below.
Asking for information.
In general, the setters are used to ensure data integrity.
This is also a security issue. You may have sensitive data, like
passwords or payroll information, which you want to control access
to.
16
Objects and Static Attributes
Static Attributes
// Get the Name of the
If an attribute is static, and the class provides a setter for that Cabbie
attribute, any object that invokes the setter will change the single public static String
copy. Thus, the value for the attribute will change for all objects. getC ompanyNam e () {
return companyName ;
} 17
Encapsulation
Encapsulation and Accessor Methods
The attributes are usually defined as private so that other objects cannot access them directly. But
isn’t it necessary to inspect and sometimes change another class’s attribute? The answer is yes, of
course. Sometimes, an object needs to access another object’s attributes; however, it does not need
to do it directly.
A class should be very protective of its attributes for several reasons; the most important ones boil
down to data integrity and efficient debugging.
Assume that there is a bug in the Cab class. You have tracked the problem to the Name attribute.
Somehow, it is getting overwritten, and garbage is turning up in some name queries. Name were
public you would have to search through all the possible codes, trying to find places that reference
and change Name. However, if you only let a Cabbie object change its name, you’d only have to
look in the Cabbie class.
An accessor is a type of method that provides this access. Sometimes accessors are referred to as
getters and setters, and sometimes they’re simply called get() and set(). By convention, in this
book we name the methods with the set and get prefixes, as in the following.
18
Encapsulation: Data Hiding
• Encapsulation bundles data (attributes) and methods that operate on the data into a single unit (a
class).
• Data Hiding is achieved by restricting direct access to attributes using access modifiers (typically
private).
• This protects the internal state of an object from unintended modifications.
• It allows you to control how and when data is accessed or modified.
• Encapsulation promotes modularity and reduces dependencies between classes.
• Benefits of Encapsulation:
• Data Integrity: Prevents unintended modifications, ensuring data consistency. final
modifier guarantees an additional layer of integrity.
• Code Maintainability: Changes to internal implementation do not affect external code
(if interfaces remain the same).
• Modularity: Classes become self-contained units, improving code organization.
• Flexibility: Allows you to change the internal implementation without breaking other
parts of the system.
• Security: Restricts access to sensitive data.
• Encapsulation allows for abstraction, as the internal implementation details are hidden
from the user.
• It is a fundamental principle that leads to more robust, scalable, and maintainable
software.
20
Constructors
Constructors in Cabbie Class
This Cabbie class contains two constructors. We know they are constructors because they have the
same name as the class: Cabbie.
Default Constructor:
public Cabbie () {
name = null ;
myCab = null ;
}
Technically, this is not a default constructor (but has a similar behavior). The default constructor is
only provided if you provide no constructors in your code. In this constructor, the attributes Name
and myCab are set to null: name = null; myCab = null;
The Nothingness of null
In many programming languages, the value null represents a value of nothing. This might seem
like an esoteric concept, but setting an attribute to nothing is a valuable programming technique.
You can check whether an attribute has been properly set by setting the attribute to null (a valid
condition). 21
Initializing Attributes in Constructors
As we know, initializing attributes in the constructors is always a good idea. In the same
vein, it’s a good programming practice to test the value of an attribute then to see whether
it is null. This can save you a lot of headaches later if the attribute or object is not set
correctly. An exception might be generated if you treat an uninitialized reference as if it
were properly initialized.
The second constructor provides initializes the Name and myCab attributes:
public Cabbie ( String iName , String serialNumber ) {
name = iName ;
myCab = new Cab ( serialNumber ) ;
}
In this case, the user would provide two strings in the constructor’s parameter list to
properly initialize attributes. Notice that the myCab object is instantiated in this constructor:
myCab = new Cab ( serialNumber ) ;
22
Inheritance
Inheritance: Code Reuse and Hierarchy
• Superclass (Base Class): The class being inherited from. It provides common
attributes and methods.
• Subclass (Derived Class): The class that inherits from the superclass. It can add
new attributes and methods or override existing ones.
• Subclasses can access non-private members of the superclass.
• The extends keyword is used to establish an inheritance relationship in Java.
public class I n h e r i t a n c e E x a m p l e {
public static void main ( String [] args ) {
Dog myDog = new Dog () ;
myDog . name = " Buddy " ; // Inherited attribute
myDog . eat () ; // Inherited method
myDog . bark () ; // Subclass - specific method
}
}
24
Inheritance: Method Overriding
• Public Interface Methods define how other objects interact with a class.
• They are declared public and represent the class’s contract with the outside world.
• These methods tend to be more abstract, focusing on what the class does rather than
how it does it.
• Examples include constructors, accessors (getters/setters), and methods that provide
core functionalities.
Example: giveDestination()
public void gi ve De s ti na ti o n () {
// Im plementa tion details are hidden here
}
Key Point: The user of the class only needs to know that calling giveDestination() will
allow them to specify a destination. They don’t need to know the inner workings of how the
destination is handled.
26
Private Implementation Methods: Encapsulation
• Private Implementation Methods are internal methods that handle the class’s
internal logic.
• They are declared private and are not accessible from outside the class.
• These methods tend to be more concrete, focusing on the specific steps needed to
achieve a task.
• They support the public interface methods by providing the necessary implementation
details.
Example: turnRight() and turnLeft()
private void turnRight () {
// Code to turn right
}
Analogy:
28
Conclusion
In this chapter, we have delved into a class and described the fundamental concepts
necessary for understanding how a class is built. Although this chapter takes a practical
approach to discussing classes, Chapter 5, ”Class Design Guidelines,” covers the class from
a general design perspective.
This lesson is based on Chapter 4 of ”The Object-Oriented Thought Process”.
29
Object-Oriented Design
• No Isolation: No matter how well you think out the problem of what should be an
interface and what should be part of the implementation, the bottom line always
comes down to how useful the class is and how it interacts with other classes.
• Contextual Design: A class should never be designed in a vacuum, for as might be
said, no class is an island. When objects are instantiated, they almost always interact
with other objects.
• Hierarchy and Composition: An object can also be part of another object or be part
of an inheritance hierarchy.
30
MC322 - Object Oriented Programming
Lesson 3
The Anatomy of a Class and Revision