0% found this document useful (0 votes)
4 views42 pages

Aula 3 - Anatomy of A Class

This document provides an overview of fundamental concepts in object-oriented programming, focusing on classes and objects. It explains the anatomy of a class, including its components such as attributes, methods, and constructors, as well as the importance of encapsulation and data integrity. Additionally, it discusses the significance of comments and documentation in code, particularly in Java using Javadoc.

Uploaded by

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

Aula 3 - Anatomy of A Class

This document provides an overview of fundamental concepts in object-oriented programming, focusing on classes and objects. It explains the anatomy of a class, including its components such as attributes, methods, and constructors, as well as the importance of encapsulation and data integrity. Additionally, it discusses the significance of comments and documentation in code, particularly in Java using Javadoc.

Uploaded by

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

MC322 - Object Oriented Programming

Lesson 3
The Anatomy of a Class and Revision

Prof. Marcos M. Raimundo


Instituto de Computação - UNICAMP
Fundamental Concepts
What is a Class?

• A class is a blueprint or a template for creating objects.


• It defines the attributes (data) and methods (behaviors) that objects of that class will
have.
• Think of it as a cookie cutter; it defines the shape, but you need to use it to create
actual cookies.
• From ”The Object-Oriented Thought Process”: A class is a description of a set of
objects that share a common structure and a common behavior.
• In code, a class encapsulates data and the methods that operate on that data.

1
What is an Object?

• An object is an instance of a class. It is a concrete realization of the class’s blueprint.


• Objects have their own unique state (values of their attributes) and can perform
actions (call methods).
• Think of it as an actual cookie made from the cookie cutter.
• From ”The Object-Oriented Thought Process”: An object is a tangible entity that
exhibits some well-defined behavior.
• Objects interact with each other by sending messages (calling methods).

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 {
}

Using Java Syntax


Remember that the convention for this book is to use Java syntax. The syntax will be
similar but somewhat different in C#, .NET, VB .NET, or C++, and totally different in
other object-oriented languages such as Smalltalk.
5
Comments
Comments in Different Languages
Regardless of the syntax of the comments used, they are vital to understanding the function
of a class. There are two kinds of comments in Java, C .NET, and C++.
The Extra Java and C# Comment Style
In Java and C, there are actually three types of comments. In Java, the third comment
type (** **) relates to a form of documentation that Java provides. We will not cover this
type of comment in this book. C provides similar syntax to create XML documents.

The first comment is the old C-style


comment, which uses /* (slash-asterisk) to The second type of comment is the //
open the comment and */ (asterisk-slash) to (slash-slash), which renders everything after
close the comment. it, to the end of the line, a comment.
/∗ // Name o f t h e c a b b i e
This c l a s s d e f i n e s a c a b b i e and a s s i g n s a cab
∗/

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)

• Javadoc is Java’s standard documentation generator.


• Docstrings are written as multi-line comments starting with /** and ending with */.
• Javadoc comments are placed directly before class, method, or field declarations.
• They allow you to generate HTML documentation from your source code.
• Use @ tags to add structured information:
• @param for method parameters
• @return for method return values
• @throws for exceptions
• @see for related classes or methods
• @author for the author
• @version for the version

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 ” ;

Name Attribute: The second attribute, name, is a string


that stores the cabbie’s name. This attribute is also private
so other objects cannot access it directly. They must use Object memory allocation.
the interface methods.
Passing a Reference
p r i v a t e S t r i n g name ;
Another object likely created the Cab
myCab Attribute: The myCab attribute is a reference to object. Thus, the object reference would
be passed to the Cabbie object. However,
another object. The class, called Cab, holds information
for the sake of this example, the Cab is
about the cab, such as its serial number and maintenance
created within the Cabbie object.
records. Likewise, for this example, we are not
p r i v a t e Cab myCab ; interested in the internals of the Cab
11
object.
Data Types and Attribute Initialization
• Data Types: Attributes can be of two main types: Primitive Types: Store actual values directly (e.g.,
int, double, boolean, char); Reference Types: Store memory addresses of objects (e.g., String,
custom classes, arrays).
• Attribute Initialization: Setting initial values for attributes.
• Prevents unexpected behavior or errors due to uninitialized values.
• Ensures objects start in a predictable state.
• Reduces the risk of NullPointerException for reference types.
public class Example {
int count = 0; // Primitive init ializati on
String name = " Default " ; // Reference initial ization
Object obj = null ; // Explicit null initiali zation
double [] values = new double [10]; // Array init ializati on
}

• 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

Attribute modifiers control the accessibility and behavior of class attributes.

• 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

• Messaging is the mechanism by which objects communicate with each other.


• It involves one object calling a method of another object, passing parameters if needed.
• The calling object ”sends a message” to the receiving object, requesting it to perform a
specific action.
• The receiving object executes the method and may return a result.
public class Example {
public static void main ( String [] args ) {
Calculator calc = new Calculator () ;
int sum = calc . add (5 , 3) ; // Sending a message to the Calculator
object
System . out . println ( " Sum : " + sum ) ;

double result = calc . divide (10.0 , 2.0) ; // Another message


System . out . println ( " Result : " + result ) ;
}
}

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

getCompanyName method is declared static as a class method and


attribute companyName is also declared static. Like an attribute, a
method can be declared static to indicate only one copy of the method
for the entire class.
Objects
Actually, there isn’t a physical copy of each non-static method for
each object. Each object would point to the same physical code.
However, from a conceptual level, you can think of objects as being
wholly independent and having their own attributes and methods. Method memory allocation.

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.

public class BankAccount {


private double balance ; // Encapsulated attribute
public void deposit ( double amount ) {
if ( amount > 0) {
balance += amount ;
}
}
public double getBalance () {
return balance ;
}
}
19
Encapsulation: The Cornerstone of Good OO Design

• 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

• Inheritance is a mechanism where a new class (subclass/derived class) inherits


properties and behaviors from an existing class (superclass/base class).
• It promotes code reuse by allowing subclasses to extend or modify the functionality of
the superclass.
• It establishes an ”is-a” relationship between classes (e.g., a ”Dog” is an ”Animal”).
• Inheritance creates a hierarchical structure of classes.
class Animal {
String name ;
void eat () {
System . out . println ( " Animal is eating . " ) ;
}
}
class Dog extends Animal { // Dog inherits from Animal
void bark () {
System . out . println ( " Dog is barking . " ) ;
}
} 23
Inheritance: Superclass and Subclass

• 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

• Method Overriding allows a subclass to provide a specific implementation of a


method that is already defined in its superclass.
• The subclass method must have the same signature (name, parameters, return type) as
the superclass method.
• The @Override annotation (in Java) is used to indicate that a method is intended to
override a superclass method.
class Animal {
void makeSound () {
System . out . println ( " Animal makes a sound . " ) ;
}
}
class Cat extends Animal {
@Override
void makeSound () {
System . out . println ( " Cat meows . " ) ;
}
} 25
Interfaces and Implementation
Public Interface Methods: Abstraction

• 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
}

private void turnLeft () {


// Code to turn left
}
27
Reinforcing Interfaces and Implementation

• Separation of Concerns: Interfaces define ”what” a class can do, while


implementation defines ”how” it does it.
• Maintainability: Changes to private methods do not affect external code, as long as
the public interface remains the same.
• Flexibility: Allows for internal changes without breaking client code.
• Abstraction: Simplifies the use of a class by hiding complex implementation details.
• Security: Prevents direct access to sensitive internal data and methods.

Analogy:

• A car’s steering wheel (public interface) allows you to turn.


• The internal mechanisms that control the wheels (private implementation) are hidden.

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

Prof. Marcos M. Raimundo


Instituto de Computação - UNICAMP

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy