0% found this document useful (0 votes)
24 views58 pages

Lecture 10 - 27-Feb-2025

Chapter 4 focuses on writing classes in Java, covering class definitions, encapsulation, method declarations, and object relationships. It emphasizes the importance of encapsulation, where instance data is protected from external access, and the use of accessors and mutators for data management. The chapter also discusses constructors, method parameters, and the scope of variables within classes.

Uploaded by

L A A
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)
24 views58 pages

Lecture 10 - 27-Feb-2025

Chapter 4 focuses on writing classes in Java, covering class definitions, encapsulation, method declarations, and object relationships. It emphasizes the importance of encapsulation, where instance data is protected from external access, and the use of accessors and mutators for data management. The chapter also discusses constructors, method parameters, and the scope of variables within classes.

Uploaded by

L A A
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/ 58

Chapter 4

Writing Classes
Writing Classes
• We've been using predefined classes. Now we will learn to write our
own classes to define objects

• Chapter 4 focuses on:


• class definitions
• encapsulation and Java modifiers
• method declaration, invocation, and parameter passing
• method overloading
• method decomposition
• graphics-based objects

2
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Relationship between an object and a class
• Class
• Blueprint of an object
• The blueprint defines the important characteristics of object
• Blueprint of a house defines (walls, windows, doors, etc)
• Once blueprint created => use it to build objects (houses)
• represents the concept of an object
• Any object created is a realization of the concept
• Example
• String class (concept) => String object (specific characters)
Another example
• Suppose a class
• Called student represents a particular student
• Student is the general concept of a student
• who has (name, address, Major, GPA)
• To whom you need (to set address, major, compute GPA)
• Every object created => an actual student
• In a system
• that helps manage the business of a university
• one student class and 1000s of student objects
Example of Classes
Object
• An object
• has a state defined by the attributes associated with that object
• Attributes of student => Student’s name, address, major, etc..
• stores the values of attributes for a particular student
• whose attributes defined by variables declared within a class
Object
• An object
• has behaviors defined by the operations associated with that object
• Operations of a student => update student’s address, GPA etc
• executes the operations defined by the class
• whose operations defined by methods declared within a class
Classes
• A class can contain data declarations and method declarations

int size, weight;


Data declarations
char category;

Method declarations
Classes and objects
• Consider a six-sided die (singular of dice)
• its state can be defined as which face is showing (integer called FaceValue)
• its primary behaviour (method) is that it can be rolled: setting its value to a
random number between one and six

• We can represent a die in software


• By designing a class called Die that models this state and behaviour. This
class would serve as the blueprint for a die object

• We can then instantiate


• As many die objects as we need for our program
Classes
• We’ll want to design the Die class that it is a versatile and reusable
resource
• Any given program will not necessarily use all aspects of a given class
• See RollingDice.java

• See Die.java
The Die Class
• The Die class contains two data values
• a constant MAX that represents the maximum face value
• an integer faceValue that represents the current face value
• The roll method uses the random method of the Math class to
determine a new face value
• There are also methods to explicitly set and retrieve the current face
value at any time
The toString Method
• All classes that represent objects should define a toString method
• The toString method returns a character string that represents the
object in some way
• It is called automatically when an object is concatenated to a string or
when it is passed to the println method
Constructors
• A constructor is a special method that is used to set up an object
when it is initially created
• A constructor has the same name as the class
• The Die constructor is used to set the initial face value of each new
die object to one
Data Scope
• The location at which a variable is declared defines its scope , which is
the area within a program in which that variable can be referenced.
• Data declared within a method can be used only in that method
• Data declared within a method is called local data
• In the Die class, the variable result is declared inside the toString
method -- it is local to that method and cannot be referenced anywhere
else
Instance Data
• A variable declared at the class level (such as faceValue) is called instance data
• Each instance (object) has its own instance variable
• A class declares the type of the data, but it does not reserve any memory space for it
• Every time a Die object is created, a new faceValue variable is created as well
• The objects of a class share the methods but each object has its own data space
• That's the only way two objects can have different states
Instance Data
• We can depict the two Die objects from the RollingDice program as
follows
die1 faceValue 5

die2 faceValue 2

Each object maintains its own faceValue


variable, and thus its own state
Quick Check
• What is the relationship between a class and an object?

A class is the definition/pattern/blueprint of an object. It defines the


data that will be managed by an object but doesn’t reserve memory
space for it.
Multiple objects can be created from a class and each object has its
own copy of instance data.
Quick Check
• Where is instance data declared?
• What is local data?
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Encapsulation
• The instance data of an object should be modified only by that object:
self-governing. For example, the methods of the Die class should be
solely responsible for changing the value of the faceValue variable.
• We should make it difficult, if not impossible, for code outside of a
class to “reach in” and change the value of a variable that is declared
inside that class. This characteristic is called encapsulation .
• An object should be encapsulated from the rest of the system.
• It should interact with other parts of a program only through the
specific set of methods that define the services that that object
provides.
• These methods define the interface between that object and the
program that uses it.
Encapsulation
• An encapsulated object can be thought of as a black box – its
inner workings are hidden from the client
• The code that uses an object, sometimes called the client of an
object, should not be allowed to access variables directly. The
client should call an object’s methods, and those methods then
interact with the data encapsulated within the object.
• For example, the main method in the RollingDice program calls
the roll method of the Die objects.
• The main method should not (and in fact cannot) access the
faceValue variable directly.

• In Java, we accomplish object encapsulation using modifiers .


Visibility modifiers
• A modifier is a Java reserved word that is used to specify particular characteristics of
a programming.
• Some of the Java modifiers are called visibility modifiers because they control access
to the members of a class.
• The reserved words public and private are visibility modifiers that can be applied to
the variables and methods of a class.
• If a member of a class has public visibility , it can be directly referenced from outside
of the object.
• f a member of a class has private visibility , it can be used anywhere inside the class
definition but cannot be referenced externally.
• A third visibility modifier, protected , is relevant only in the context of inheritance.
Public and Private visibility
• Public variables violate encapsulation because they allow code external to
the class in which the data is defined to reach in and access or modify the
value of the data.
• Instance data should be defined with private visibility.
• Data that is declared as private can be accessed only by the methods of the
class.
• Methods that provide services to the client must be declared with public
visibility so that they can be invoked by the client. These methods are
sometimes referred to as service methods .
• A private method cannot be invoked from outside the class. The only
purpose of a private method is to help the other methods of the class do
their job. Therefore, they are sometimes referred to as support methods .
Effects of public and private visibility
Accessors and mutators
• Instance data is generally declared with private visibility, a class usually provides
services to access and modify data values.
• A method such as getFaceValue is called an accessor method because it provides
read-only access to a particular value.
• A method such as setFaceValue is called a mutator method because it changes a
particular value.
• These types of methods are sometimes Referred to as “getters” and “setters”
• The name of an accessor method take the form getX
• Where X is the name of value
• The name of a mutator method take the form setX

Some methods may provide accessor and/or mutator capabilities as a side effect of their primary
purpose. For example, the roll method of the Die class changes the faceValue of the die and returns
that new value as well. Therefore, roll is also a mutator method.
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Method
• A method is a group of programming language statements that is given a
name
• A method declaration specifies the code that is executed when the method
is invoked.
• Every method in a Java program is part of a particular class.
• When a method is called:
• One by one, the statements of that method are executed
• The header of a method includes the type of the return value, the method
name, and a list of parameters that the method accepts.
• The statements that make up the body of the method are defined in a
block delimited by braces.
Method Declaration
Method Control flow

• The called method is often part of another class or object


• If called method and calling method
• Same class => only method name is needed
• Different class => invoke through the name of other class
Method Header
• A method declaration begins with a method header
char calc (int num1, int num2, String message)

method
parameter list
name

return The parameter list specifies the type


type and name of each parameter

The name of a parameter in the method


declaration is called a formal parameter
Method Body
• The method header is followed by the method body
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);

return result; sum and result


} are local data

They are created


The return expression each time the
must be consistent with method is called, and
the return type are destroyed when
it finishes executing
The return Statement
• The return type of a method indicates
• the type of value that the method sends back to the calling location

• Method returning no value has a void return type


• A return statement specifies the value that will be returned
return expression;

• A method should have one return statement as the last line of the
method body
The return statement is used to exit a method and optionally send a value back to the calling method.
40
Return Statement
• Return type specified in method header
• Primitive type or class name
• When the method returns a value
• In this case, the method must have a return statement
• Return statement : return + value to be returned

• Or, the reserved word “void”


• When a method does not return any value
• In this case, the method does not contain a return statement
• Control is returned to calling method at the end of the method

The return statement is optional in void methods.


If used, return; simply exits the method.
If you don’t write return;, Java automatically exits the method at the end.
Parameters
• The parameter is a value that is passed into a method when it is
invoked.
• The parameter list in the header of a method specifies the types of
the values that are passed and the names by which the called method
will refer to those values.
• The names of the parameters in the header of the method
declaration are called formal parameters .
Parameters
• When a method is called, the actual parameters in the invocation are
copied into the formal parameters in the method header
Local Data
• Local variables can be declared inside a method
• The formal parameters of a method create automatic local variables
when method is invoked
• When the method finishes, all local variables are destroyed (including
the formal parameters)
• Instance variables declared at the class level exists as long as the
object exists
Bank Account Example
• Example demonstrates implementation details of classes and methods
• bank account by a class named Account
• Its State can include the account number, the current balance, and the name of the owner
• An account’s behaviors (or services) include deposits and withdrawals, and adding interest
Driver Programs
• A driver program drives the use of other, more interesting parts of a
program

• Driver programs are often used to test other parts of the software
• The Transactions class contains a main method that drives the
use of the Account class, exercising its services

• See Transactions.java (page 172)


• See Account.java (page 173)
Bank Account Example
Bank Account Example
• There are some improvements that can be made to the Account
class
• Formal getters and setters could have been defined for all data
• The design of some methods could also be more robust, such as
verifying that the amount parameter to the withdraw method is
positive
Constructors revisited
• A constructor has no return type specified in the method header, not
even void
• A common error is to put a return type on constructor, which makes it
a regular method that happens to have the same name as the class
• When we define a class
• We usually define a constructor
• A method that helps setting the class up
• Often used to initialize variables associated with each object
Constructors revisited
• Constructor
• is used to initialize the newly instantiated object

• Don’t have to define a constructor for every class

• Each class has a default constructor taking no parameters

• This default constructor is used if you don’t provide your own

• Default constructor has no effect on the newly created object


Summary
• The heart of object-oriented programming is defining classes that
represent objects with well-defined state and behavior.
• The scope of a variable, which determines where it can be
referenced, depends on where it is declared.
• An object should be encapsulated, guarding its data from
inappropriate access.
• Instance variables should be declared with private visibility to
promote encapsulation.
Summary
• Most objects contain accessor and mutator methods to allow the
client to manage data in a controlled manner.
• The value returned from a method must be consistent with the return
type specified in the method header.
• When a method is called, the actual parameters are copied into the
formal parameters.
• A variable declared in a method is local to that method and cannot be
used outside of it.
• A constructor cannot have any return type, even void.

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