SlideShare a Scribd company logo
Lesson 4 – Classes & Objects
UNIT D1 – INTRODUCTION
Container vs. Definition classes
 Generally, classes can be used for two
purposes:
 Container classes:
 a collection of static methods that are not
bound to any particular object (e.g., the main()
method).
 These static methods usually have something in
common
 Definition classes:
 These classes define new objects, in a way that
we will soon see.
Container vs. Definition Classes -
Example
 The Math class is an example of the first kind. It is a
container for math utility methods: Math.sqrt(),
Math.abs(), Math.max(), ...
 The class Turtle is an example of the second kind. It
defines a new type of objects, Turtle objects.
 We will now focus on the second kind.
Class Abstraction
 The most important stage in writing a class is to get an
abstraction of the class done first.
 What does an object of this type represent?
 What is its interface?
 What is its internal state?
 This means you have to know what should be the internal
state (variables) and also the behavior/interface
(methods) of the class before you start to write you class
code.
Objects and Classes
 The relationship between Classes and Objects can be seen as
the relationship between a blueprint/model and the the
actual object built from it.
 Example: Blueprint of a house (class) and the house (object)
 The class defines:
 The type of data that will be held in an object
 The code for the methods of the object
 In order to use a class you must instantiate an object from it.
 This corresponds to building the house from the blueprint.
 There may be many objects from a single class
Turtle Class Abstraction
 A Turtle represents a creature moving on the screen
with a pen attached to its tail
 The internal state of a Turtle includes:
 Location on screen; direction of movement; tail up/down
 The interface of a Turtle is:
Turtle();
void moveForward(double units);
void moveBackward(double units);
void turnLeft(double degrees);
// …
Encapsulation
 The internal state of an object is not directly accessible to
other parts of the program
 Other parts of the program can only access the object
using its interface
 We say that the state is
encapsulated or hidden
 This gives modularity
to the program
moveForward()
turnRight()
.
.
.
.
.
.
•tailDown
•x,y
•direction
Clock Class Abstraction
 A Clock represents a 12-hour clock
 Its internal state includes: hour, minute, second
 Its interface allows telling the clock that a second has
elapsed, and querying the clock for the time:
Clock(int hours, int minutes, int seconds)
int getSeconds()
void secondElapsed()
int getMinutes()
int getHours()
...
Using a Clock class
Clock newYorkTime = new Clock(12,59,59);
for (int j = 0; j < 3; j++)
newYorkTime.secondElapsed();
System.out.println(newYorkTime.getHours() +
“:” + newYorkTime.getMinutes() +
“:” + newYorkTime.getSeconds());
Structure of the Clock class
 The private modifier specifies an identifier that is only visible
within the class. Usually used for fields.
 The public modifier specifies an identifier that is accessible to all
other classes. Usually used for methods.
public class Clock {
private int hours, minutes, seconds;
public Clock(int h, int m, int s){ … }
public void secondElapsed() { … }
public int getHours() { … }
public int getMinutes() { … }
public int getSeconds() { … }
}
Lesson 4 – Classes & Objects
UNIT D2 - CLASS ELEMENTS
Instance Variables
 Recall that a class must define the state of an object and
its behavior.
 We declare state variables (variables that hold the state of
the object) in a similar way to that of regular variables,
only they appear outside methods, inside the class.
 State variables are also called instance variables or fields.
 Roughly speaking, the private modifier means that the
variables are not part of the object’s interface.
public class Clock {
private int hours, minutes, seconds;
// …
}
Constructors
 Objects must be initialized before they can be used.
 We must specify what is the initial state of the object
before we can use it.
 Space for holding the object state data is only allocated
when the object is constructed.
 We specify the way an object is initialized using a
constructor, which is a special method which is invoked
every time we create a new object
 The name of the constructor is always identical to the
class name
Clock Constructor
public Clock(int h, int m, int s){
hours = h;
minutes = m;
seconds = s;
}
Clock constructor invoked
public class Clock {
private int hours, minutes,seconds;
public Clock(int h, int m, int s){
hours = h;
minutes = m;
seconds = s;
}
// …
C:
10
45
0
Clock c;
c = new Clock(10,45,0);
hours:
Minutes:
Seconds:
Methods
 To make the date object useful, we must provide methods
that define its behavior.
 We declare methods in a similar way to the way the
method main was declared.
 Only there’s a big difference:
 the main method was static, which
means it wasn’t bound to a specific
object
 we want to declare instance methods,
which operate on a specific instance of
an object
secondElapsed() method
public void secondElapsed() {
if (seconds < 59) seconds++;
else {
seconds=0;
if (minutes < 59) minutes++ ;
else {
minutes = 0;
hours = hours < 12 ? hours+1 : 1;
}
}
}
Return Types
 Methods may return values
 The return type of a method indicates the type of value that
the method sends back to the calling client
 The return-type of getHours() is int. When a client ask
for the hours read of a clock it gets the answer as an int
value.
 A method that does not return a value (such as
secondElapsed()) has a void return type
 The return statement specifies the value that should be
returned, which must conform with the return type of the
method.
Clock accessor methods
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
Method Context
 The getHours() and secondElapsed() methods are
instance methods, which means they act on a particular
instance of the class
 They cannot be invoked “out of the blue”. They must act on a
particular object:
 An instance method is executed in the context of the
object it acts upon.
Clock c = new Clock(1,2,3);
getHours(); // Error!! of which clock?
c.getHours(); // will return 1
ClockTest example
public class ClockTest {
public static void main(String[] args) {
Clock swatch = new Clock(12,59,59);
Clock seiko = new Clock(12,59,59);
System.out.println(swatch.getHours()); // 12
System.out.println(seiko.getHours()); // 12
swatch.secondElapsed();
System.out.println(swatch.getHours()); // 1
System.out.println(seiko.getHours()); // 12
}
}
Method Parameters
 A method can be defined to accept zero or more
parameters
 Each parameter in the parameter list is defined by its type
and name
 The parameters in the method definition are called formal
parameters
 The values passed to a method when it is invoked are
called actual parameters
 The name of the method together with the list of its
formal parameters is called the signature of the method
public void setTime(int h, int m, int s)
Method setTime()
public void setTime(int h, int m, int s){
if ((s >= 0) && (s < 60) &&
(m >= 0) && (m < 60) &&
(h > 0) && (h <= 12)) {
hours = h;
minutes = m;
seconds = s;
}
// no effect if input is illegal
}
Lesson 4 – Classes & Objects
UNIT D3 - METHOD WRITING DETAILS
Variable Scope
 Variables may be declared in:
 Class – state variables
 Method/constructor – local variables (and parameters)
 Inner block of a method – also local variables
 A variable is recognized throughout the block in which it was
defined. This is called the scope of the variable.
 Local variables are allocated when the method is entered and
freed when the method exits.
 The same name may be used in different scopes, and refer to
totally different things
 If the same name is used in an outer and inner scope, then
the inner scope definition “hides” the outer one.
The this reference
 When appearing inside an instance method, the this
keyword denotes a reference to the object that the
method is acting upon.
 The following are equivalent:
public int getHours() {
return hours;
}
public int getHours() {
return this.hours;
}
Using same names for parameters
and fields
 It is usually bad practice to use the same name for a state
variable and a local variable or parameter.
 Exception: parameters that correspond exactly to fields
public void setTime(int hours,
int minutes,
int seconds) {
if ((seconds >= 0) && (seconds < 60) &&
(minutes >= 0) && (minutes < 60) &&
(hours > 0) && (hours <= 12)) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
// no effect if input is illegal
}
Passing Parameters
 When a parameter is passed, a copy of the value is made
and assigned to the formal parameter:
Clock beritling = new Clock(1,2,3);
int lunchHour = 12;
breitling.setTime(lunchHour,32,14);
hours = lunchHour
minutes = 32
seconds = 14
Parameters are passed by value
Clock c = new Clock(1,2,3);
int a= 7;
c.funnyGetHour(a); // still 7!!
class Clock {
// …
public void funnyGetHour(int h){
h = hours;
}
}
Passing Object parameters
 When an Object is a parameter, only the reference is
passed by value. The parameter now is an alias of the
object.
class XX {
// …
public void setMidnight(Clock c) {
c.setTime(12,0,0);
}
class YY {
// …
XX x = new XX();
Clock myClock = new Clock(1,2,3);
x.setMidnight(myClock); // 12:0:0
Example: A Bank Account Object
public BankAccount(long accountNumber)
public void deposit(double amount)
public void withdraw(double amount)
public double getBalance()
public void transfer(double amount,
BankAccount targetAccount)
BankAccount
Bank Account - example
public class BankAccount {
private long accountNumber;
private double balance;
public BankAccount(long accountNumber){
this.accountNumber = accountNumber;
balance = 0;
}
public double getBalance() {
return balance;
}
// continued in the next slide...
}
Bank Account - example
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
public void transfer(double amount,
BankAccount targetAccount){
withdraw(amount);
targetAccount.deposit(amount);
}
Bank Account – usage example
BankAccount aliceAcc = new BankAccount(1398723);
BankAccount bobAcc = new BankAccount(1978394);
aliceAcc.deposit(900);
aliceAcc.transfer(700,bobAcc);
// Alice’s balance = 200 ; Bob’s balance = 700
Constructor and Method
Overloading
 A class can define several constructors -- several ways to
initialize an instance of this class
 These constructors differ by the number and/or type of
parameters they get.
 When we construct an object, the compiler decides which
constructor to invoke according to the number and types of
the actual arguments
 A constructor with no parameters is called the default
constructor
 Different methods can also use the same name as long as
they differ in the number or type of parameters.
 When we invoke a method, the compiler decides which
method to invoke according to the number and types of the
actual arguments
Constructor Overloading example
public Clock(int h, int m, int s){
hours = h;
minutes = m;
seconds = s;
}
public Clock(int h) {
this(h, 0 ,0);
}
public Clock() {
this(12);
}
Lesson 4 – Classes & Objects
UNIT D4 - VISIBILITY MODIFIERS
Visibility Modifiers
 We accomplish encapsulation through the appropriate use
of visibility modifiers
 Visibility modifiers specify which parts of the program may
see and use any particular class/method/field
 Information hiding is good!
 A modifier is a Java reserved word that specifies particular
characteristics of a programming construct
 We've used the modifier final to define a constant
 Java has three visibility modifiers: public, private, and
protected
 We will discuss the protected modifier later in the course
Visibility Modifiers - Classes
 A class can be defined either with the public modifier
or without a visibility modifier.
 If a class is declared as public it can be used by any other
class
 If a class is declared without a visibility modifier it has a
default visibility. This draws a limit to which other classes
can use this class (classes in the same package). We will
discuss default visibility later in the course.
 Classes that define a new type of objects, that are
supposed to be used anywhere, should be declared
public.
Visibility Modifiers - Members
 A member is a field, a method or a constructor of the class.
 Members of a class can be declared as private,
protected, public or without a visibility modifier:
 Members that are declared without a visibility modifier are
said to have default visibility. We will discuss default and
protected visibility later in the course.
private int hours;
int hours;
public int hours;
Public Visibility
 Members that are declared as public can be accessed from
any class that can access the class of the member
 We expose methods that are part of the interface of the class
by declaring them as public
 Example: the methods getHours(), secondElapsed()
and setTime() are part of the interface of class Clock so
we define them as public.
 We do not want to reveal the internal representation of the
object’s data. So we usually do not declare its state variables
as public (encapsulation)
Private Visibility
 A class member that is declared as private, can be
accessed only by code that is within the class of this
member.
 We hide the internal implementation of the class by
declaring its state variables and auxiliary methods as
private.
 Data hiding is essential for encapsulation.
Illegal Access - example
// Example of illegal access
class BankAccountTest {
public static void main(String[] args) {
BankAccount victim = new BankAccount(2398742);
victim.balance = victim.balance - 500;
// this will not compile!
}
}
public class BankAccount {
private long accountNumber;
private double balance;
// …
Encapsulation not Among Instances of Same
Class
 Encapsulation is to protect the programmers and is thus
between the code of different classes
 Sometimes object instances of the same class need to
access each other’s “guts” (e.g., for state copying - if we
want to create an identical instance of an object we have)
 Example:
 from within a BankAccount object, any private member of
a different BankAccount object can be accessed.
Encapsulation - example
public void transfer(double amount,
BankAccount targetAccount) {
withdraw(amount);
targetAccount.deposit(amount);
}
// alternative version (valid, but not so nice)
public void transfer(double amount,
BankAccount targetAccount) {
balance -= amount;
targetAccount.balance += amount;
}
Lesson 4 – Classes & Objects
UNIT D5 - API DOCUMENTATION
API Documentation
 Your classes are often intended to be used by other
programmers
 Programmers that use your class are not interested in the
way it is implemented. They want to use it as a whole and
are only interested in what it does and how to use it.
 API (Application Programmer Interface) documentation is
a description of the interface of the class intended for the
application programmer who wants to use it.
 To use the class, we need not (and should not) look at the
code. All that is needed is the class API.
API Documentation
 The JDK contains a special tool for the generation of API
documentation for your classes, called javadoc.
 Any documentation which is part of the interface begins
with /** (double asterick) and ends with */
 javadoc takes as input Java programs and automatically
generates documentation using:
 the public/protected method signatures
 the documentation comments (enclosed by /** … */).
 The output is an HTML file which can be viewed by an
internet browser.
Clock API Documentation
/**
* A clock represents a point of time in a 12
* hour period within a precision of seconds.
* Its range: 1:00:00 -- 12:59:59.
*/
public class Clock {
private int hours;
private int minutes;
private int seconds;
/**
* Constructs a Clock: Sets the clock to the
* specified time.
*/
public Clock(int hours, int minutes, int seconds){
//…
}
Clock API Documentation – cont.
/**
* Constructs a Clock: Sets the clock to 12:00:00
*/
public Clock(){
this(12,0,0);
}
/**
* Advances this clock by 1 second.
*/
public void secondElapsed() {
//…
}
//…
Javadoc Process
.java file .html file
javadoc
View using a
browser
Clock javadoc - page 1
Clock javadoc - page 2
What should you comment?
 You should put a documentation comment for the class
itself and for any member of the class which is part of its
interface.
 All public constructors and methods should have
documentation comments.
 Private methods are not part of the interface of the
class, thus javadoc skips them. (But you should still
comment them for internal purposes.)
 In the rare cases that there are public fields, they should
have documentation comments.
API Documentation
 Remember that documentation comments are written for
programmers who use your class as a whole. They should describe
only
 What the class does,
 How to use it.
 Documentation comments should not describe how a class is
implemented.
 Documentation comments should be
 Short and descriptive,
 Written in a simple language (ENGLISH),
 Accurate.
 Assume that the reader doesn’t know anything about your class
API Documentation Tags
 Documentation comments can also include tagged
paragraphs that give a standard way to document several
features of the interface such as method parameters,
return values, etc.
 A tagged paragraph begins with the symbol @ followed
with a tag keywords. Tags: @see, @author,
@version, @param, @return, @exception.
 Documentation comments text can include HTML tags.
@param tag
/**
* Changes the current time to hour:minute:second
* @param hours The new hour value.
* @param minutes The new minutes value.
* @param seconds The new seconds value.
*/
public void setTime(int hours,
int minutes,
int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
setTime generated javadoc
@return
/**
* Returns the current hour
* @return The current hour (between 1 and 12).
*/
public void getHour() {
return hours;
}
getHour javadoc
Naming
 The names you use for your class and for its public
methods are part of the class API.
 Good descriptive naming are crucial for a clear API.
 General rules about naming:
 Follow the Java conventions
 Use descriptive names
 Do not use abbreviations!
 Make names long enough, not unnecessary long
 Consist of words in English with no abbreviations
 Use a dictionary
 Read the style guidelines!
Changing the Implementation of
a Class
 Encapsulation allows us to change an implementation of a
class without affecting other parts of the program.
 Without encapsulation changes to implementation might
“break” the program - many changes
 Why would we want to change the implementation?
 Different implementations have different tradeoffs (e.g., space
conservation, efficiency etc.)
 Example: a time instance in the day can be represented by
the number of seconds since midnight
 Assume we want to change the implementation of the clock
- what is involved in the process?
Example of new Clock
implementation - page 1
/**
* A clock represents a point of time in a 12
* hour period within a precision of seconds.
* Its range: 01:00:00 -- 12:59:59.
*/
public class Clock {
private static final int SECONDS_IN_12H = 12*60*60;
private int secondsFromZero;
/**
* Constructs a Clock: Sets the clock to the
* specified time.
*/
public Clock(int hours, int minutes, int seconds){
secondsFromZero = ((hours%12) * 3600
+ minutes * 60 + seconds);
}
Example of new Clock
implementation - page 2
/**
* Constructs a Clock: Sets the clock to 12:00:00
*/
public Clock(){
secondsFromZero=0;
}
/**
* Advances this clock by 1 second.
*/
public void secondElapsed() {
secondsFromZero = (secondsFromZero+1) %
SECONDS_IN_12H;
}
//…
Example of new Clock
implementation - page 3
/**
* Returns the current hour
* @return The current hour (between 1 and 12).
*/
public void getHour() {
int h = secondsFromZero/3600;
return h > 0 ? h : 12 ;
}
// all the others can be written in the same way
Lesson 4 – Classes & Objects
UNIT D6 - APPLET METHODS & GRAPHIC OBJECTS
Applet Methods
 We saw in earlier applets the use the of the paint
method to draw the content of the of the applet on the
screen.
 An applet has several other methods that perform
specific duties.
 Because the applets are specifically designed to work
with web browsers, some particular applet methods are
designed around that concept.
public void paint(Graphics g)
Some Applet Methods
 Initializes the applet. Called just after the applet is loaded.
 Starts the applet. Called just after the applet is made active.
 Stops the applet. Called just after the applet is made
inactive.
 Destroys the applet. Called when when the browser is
exited.
public void init()
public void start()
public void stop()
public void destroy()
Init, start, stop, and destroy.
 The init method is executed once when the applet is
first loaded, such as when the browser or the applet
viewer initially view the applet.
 This is the place to to initialize the applet’s environment and
permanent data.
 The start/stop methods of an applet are called when
the applet becomes active/inactive.
 For example, after we use a browser to initially load an
applet start is called. When we leave the page, the applet
becomes inactive and stop is called. If we return to that
page the applet becomes active again and start is called.
init start stop destroy
Objects with Graphic
representation
 Many programs are graphic
 Many objects in such programs correspond to “graphic
objects” on the screen – this is good programming
practice.
 Such a graphic object will know how to draw itself on the
screen
LineUp Applet
The Lineup programs
 The LineUp applet, shown in the previous slide shows 4
stick figures of different heights and colors.
 It uses a StickFigure class that represents a stick
figure of a certain height, color, and location.
 The applet creates 4 StickFigure objects, of varying
color and random height.
 The StickFigure objects are instantiated in the init
method of the applet, so they are created once when the
applet is loaded.
 The paint method of LineUp simply requests that the
stick figures draw themselves.
StickFigure - 1
import java.awt.*;
public class StickFigure {
private int baseX;
private int baseY;
private Color color;
private int height;
public StickFigure(int center, int bottom,
Color shade, int size) {
baseX = center;
baseY = bottom;
color = shade;
height = size;
}
StickFigure - 2
public void draw(Graphics page) {
int top = baseY – height;
page.setColor(color);
//head
page.drawOval(baseX-10,top,20,20);
//trunk
page.drawLine(baseX,top+20,baseX,baseY-30);
page.drawLine(baseX,baseY-30,baseX-15,baseY);
//legs
page.drawLine(baseX,baseY-30,baseX+15,baseY);
//arms
page.drawLine(baseX,baseY-70,baseX-25,baseY-70);
page.drawLine(baseX,baseY-70,baseX+20,baseY-85);
}
LineUp - code
import java.applet.Applet;
import java.awt.*;
public class LineUp extends Applet
{
private final int APPLET_WIDTH = 400;
private final int APPLET_HEIGHT = 150;
private final int HEIGHT_MIN = 100;
private final int VARIANCE = 30;
private StickFigure figure1, figure2,
figure3, figure4;
LineUp - code
public void init ()
{
int h1, h2, h3, h4; // heights of figures
h1 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
h2 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
h3 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
h4 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN;
figure1 = new StickFigure(100,150,Color.red,h1);
figure2 = new StickFigure(150,150,Color.cyan,h2);
figure3 = new StickFigure(200,150,Color.green,h3);
figure4 = new StickFigure(250,150,Color.yellow,h4);
setBackground(Color.black);
setSize(APPLET_WIDTH, APPLET_HEIGHT);
}
LineUp - code
public void paint (Graphics page){
figure1.draw(page);
figure2.draw(page);
figure3.draw(page);
figure4.draw(page);
}
}
Lesson 4 – Classes & Objects
UNIT D7 - STATIC AND AUXILIARY METHODS
The Static Modifier
 The static modifier can be applied to variables or
methods
 It associates a variable or method with the class rather
than an object
 Methods that are declared as static do not act upon
any particular object. They just encapsulate a given task,
a given algorithm.
 We can write a class that is a collection of static
methods. Such a class isn’t meant to define new type of
objects. It is just used as a library for utilities that are
related in some way.
Example - a Math Class
/**
* A library of mathematical methods.
*/
public class Math {
/**
* Computes the trigonometric sine of an angle.
*/
public static double sin(double x) { … }
/**
* Computes the logarithm of a given number.
*/
public static double log(double x) { … }
// ...
Static Variables
 A variable that is declared static is associated with the
class itself and not with an instance of it.
 Static variables are also called class variables.
 We use static variables to store information that is not
associated with a given object, but is relevant to the class.
 We have already seen such usage - constants of a class
(final static)
Static Variables - Example
public class BankAccount {
private long accountNumber;
private double balance;
private static int numberOfAccounts = 0;
public BankAccount() {
this.accountNumber = ++numberOfAccounts;
this.balance = 0;
}
public static int getNumberOfAccounts {
return numberOfAccounts;
}
}
Static Methods and Instance
Variables
 Static methods:
 cannot reference instance variables (e.g. - access instance
variable when an object doesn’t exist)
 can reference static variables or local variables (within the
method)
 this has no meaning inside a static method, thus its use
inside a static method is not allowed.
 Instance methods can access static variables.
Division Into Methods
 Complicated tasks or tasks that occur often within a class
should be wrapped in a method
 If you can clearly define the task, you should probably
make it a method.
 This results in a readable and manageable code
 This is very helpful when implementing algorithms, or
when we need “helper” methods in classes.
Division into methods – interest
calculation
public class BankAccount {
final static int DAYS_IN_YEAR = 365;
public void earnDailyInterest(int days){
double rate = 1 + interestRate()/DAYS_IN_YEAR;
for(int j=0 ; j<days ; j++)
balance *= rate;
}
private double interestRate() {
return (balance>100000) ? 0.06 : 0.05;
}
Division into Methods – Printing
primes
public class PrintPrimes {
public static void main(String[] args) {
for(j = 2 ; j < 1000 ; j++){
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int n){
for(int j=2 ; j < n ; j++)
if (n%j == 0)
return false;
return true;
}
}
Lesson 4 – Classes & Objects

More Related Content

Similar to Class & Objects in JAVA.ppt

Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
Unit i
Unit iUnit i
Unit i
snehaarao19
 
oops-1
oops-1oops-1
oops-1
snehaarao19
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
Mahmoud Samir Fayed
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
MiltonMolla1
 
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
Mahmoud Samir Fayed
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 
Chapter 6.5
Chapter 6.5Chapter 6.5
Chapter 6.5
sotlsoc
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class Structure
Victer Paul
 
Chapter 6.5 new
Chapter 6.5 newChapter 6.5 new
Chapter 6.5 new
sotlsoc
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 

Similar to Class & Objects in JAVA.ppt (20)

Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Unit i
Unit iUnit i
Unit i
 
oops-1
oops-1oops-1
oops-1
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
Object and class
Object and classObject and class
Object and class
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Chapter 6.5
Chapter 6.5Chapter 6.5
Chapter 6.5
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class Structure
 
Chapter 6.5 new
Chapter 6.5 newChapter 6.5 new
Chapter 6.5 new
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 

More from RohitPaul71

FiniteAutomata.ppt
FiniteAutomata.pptFiniteAutomata.ppt
FiniteAutomata.ppt
RohitPaul71
 
lecture4.pptx
lecture4.pptxlecture4.pptx
lecture4.pptx
RohitPaul71
 
Memory Managment(OS).pptx
Memory Managment(OS).pptxMemory Managment(OS).pptx
Memory Managment(OS).pptx
RohitPaul71
 
376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt
RohitPaul71
 
amer-memory1.ppt
amer-memory1.pptamer-memory1.ppt
amer-memory1.ppt
RohitPaul71
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
RohitPaul71
 
Binary Adder Design(COA).ppt
Binary Adder Design(COA).pptBinary Adder Design(COA).ppt
Binary Adder Design(COA).ppt
RohitPaul71
 
ch8.ppt
ch8.pptch8.ppt
ch8.ppt
RohitPaul71
 
4876238.ppt
4876238.ppt4876238.ppt
4876238.ppt
RohitPaul71
 
ALUdesign.ppt
ALUdesign.pptALUdesign.ppt
ALUdesign.ppt
RohitPaul71
 
Air Pollution (1).ppt
Air Pollution (1).pptAir Pollution (1).ppt
Air Pollution (1).ppt
RohitPaul71
 
memory.ppt
memory.pptmemory.ppt
memory.ppt
RohitPaul71
 
7_mem_cache.ppt
7_mem_cache.ppt7_mem_cache.ppt
7_mem_cache.ppt
RohitPaul71
 

More from RohitPaul71 (13)

FiniteAutomata.ppt
FiniteAutomata.pptFiniteAutomata.ppt
FiniteAutomata.ppt
 
lecture4.pptx
lecture4.pptxlecture4.pptx
lecture4.pptx
 
Memory Managment(OS).pptx
Memory Managment(OS).pptxMemory Managment(OS).pptx
Memory Managment(OS).pptx
 
376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt376951072-3-Greedy-Method-new-ppt.ppt
376951072-3-Greedy-Method-new-ppt.ppt
 
amer-memory1.ppt
amer-memory1.pptamer-memory1.ppt
amer-memory1.ppt
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
 
Binary Adder Design(COA).ppt
Binary Adder Design(COA).pptBinary Adder Design(COA).ppt
Binary Adder Design(COA).ppt
 
ch8.ppt
ch8.pptch8.ppt
ch8.ppt
 
4876238.ppt
4876238.ppt4876238.ppt
4876238.ppt
 
ALUdesign.ppt
ALUdesign.pptALUdesign.ppt
ALUdesign.ppt
 
Air Pollution (1).ppt
Air Pollution (1).pptAir Pollution (1).ppt
Air Pollution (1).ppt
 
memory.ppt
memory.pptmemory.ppt
memory.ppt
 
7_mem_cache.ppt
7_mem_cache.ppt7_mem_cache.ppt
7_mem_cache.ppt
 

Recently uploaded

ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 

Recently uploaded (20)

ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 

Class & Objects in JAVA.ppt

  • 1. Lesson 4 – Classes & Objects UNIT D1 – INTRODUCTION
  • 2. Container vs. Definition classes  Generally, classes can be used for two purposes:  Container classes:  a collection of static methods that are not bound to any particular object (e.g., the main() method).  These static methods usually have something in common  Definition classes:  These classes define new objects, in a way that we will soon see.
  • 3. Container vs. Definition Classes - Example  The Math class is an example of the first kind. It is a container for math utility methods: Math.sqrt(), Math.abs(), Math.max(), ...  The class Turtle is an example of the second kind. It defines a new type of objects, Turtle objects.  We will now focus on the second kind.
  • 4. Class Abstraction  The most important stage in writing a class is to get an abstraction of the class done first.  What does an object of this type represent?  What is its interface?  What is its internal state?  This means you have to know what should be the internal state (variables) and also the behavior/interface (methods) of the class before you start to write you class code.
  • 5. Objects and Classes  The relationship between Classes and Objects can be seen as the relationship between a blueprint/model and the the actual object built from it.  Example: Blueprint of a house (class) and the house (object)  The class defines:  The type of data that will be held in an object  The code for the methods of the object  In order to use a class you must instantiate an object from it.  This corresponds to building the house from the blueprint.  There may be many objects from a single class
  • 6. Turtle Class Abstraction  A Turtle represents a creature moving on the screen with a pen attached to its tail  The internal state of a Turtle includes:  Location on screen; direction of movement; tail up/down  The interface of a Turtle is: Turtle(); void moveForward(double units); void moveBackward(double units); void turnLeft(double degrees); // …
  • 7. Encapsulation  The internal state of an object is not directly accessible to other parts of the program  Other parts of the program can only access the object using its interface  We say that the state is encapsulated or hidden  This gives modularity to the program moveForward() turnRight() . . . . . . •tailDown •x,y •direction
  • 8. Clock Class Abstraction  A Clock represents a 12-hour clock  Its internal state includes: hour, minute, second  Its interface allows telling the clock that a second has elapsed, and querying the clock for the time: Clock(int hours, int minutes, int seconds) int getSeconds() void secondElapsed() int getMinutes() int getHours() ...
  • 9. Using a Clock class Clock newYorkTime = new Clock(12,59,59); for (int j = 0; j < 3; j++) newYorkTime.secondElapsed(); System.out.println(newYorkTime.getHours() + “:” + newYorkTime.getMinutes() + “:” + newYorkTime.getSeconds());
  • 10. Structure of the Clock class  The private modifier specifies an identifier that is only visible within the class. Usually used for fields.  The public modifier specifies an identifier that is accessible to all other classes. Usually used for methods. public class Clock { private int hours, minutes, seconds; public Clock(int h, int m, int s){ … } public void secondElapsed() { … } public int getHours() { … } public int getMinutes() { … } public int getSeconds() { … } }
  • 11. Lesson 4 – Classes & Objects UNIT D2 - CLASS ELEMENTS
  • 12. Instance Variables  Recall that a class must define the state of an object and its behavior.  We declare state variables (variables that hold the state of the object) in a similar way to that of regular variables, only they appear outside methods, inside the class.  State variables are also called instance variables or fields.  Roughly speaking, the private modifier means that the variables are not part of the object’s interface. public class Clock { private int hours, minutes, seconds; // … }
  • 13. Constructors  Objects must be initialized before they can be used.  We must specify what is the initial state of the object before we can use it.  Space for holding the object state data is only allocated when the object is constructed.  We specify the way an object is initialized using a constructor, which is a special method which is invoked every time we create a new object  The name of the constructor is always identical to the class name
  • 14. Clock Constructor public Clock(int h, int m, int s){ hours = h; minutes = m; seconds = s; }
  • 15. Clock constructor invoked public class Clock { private int hours, minutes,seconds; public Clock(int h, int m, int s){ hours = h; minutes = m; seconds = s; } // … C: 10 45 0 Clock c; c = new Clock(10,45,0); hours: Minutes: Seconds:
  • 16. Methods  To make the date object useful, we must provide methods that define its behavior.  We declare methods in a similar way to the way the method main was declared.  Only there’s a big difference:  the main method was static, which means it wasn’t bound to a specific object  we want to declare instance methods, which operate on a specific instance of an object
  • 17. secondElapsed() method public void secondElapsed() { if (seconds < 59) seconds++; else { seconds=0; if (minutes < 59) minutes++ ; else { minutes = 0; hours = hours < 12 ? hours+1 : 1; } } }
  • 18. Return Types  Methods may return values  The return type of a method indicates the type of value that the method sends back to the calling client  The return-type of getHours() is int. When a client ask for the hours read of a clock it gets the answer as an int value.  A method that does not return a value (such as secondElapsed()) has a void return type  The return statement specifies the value that should be returned, which must conform with the return type of the method.
  • 19. Clock accessor methods public int getHours() { return hours; } public int getMinutes() { return minutes; } public int getSeconds() { return seconds; }
  • 20. Method Context  The getHours() and secondElapsed() methods are instance methods, which means they act on a particular instance of the class  They cannot be invoked “out of the blue”. They must act on a particular object:  An instance method is executed in the context of the object it acts upon. Clock c = new Clock(1,2,3); getHours(); // Error!! of which clock? c.getHours(); // will return 1
  • 21. ClockTest example public class ClockTest { public static void main(String[] args) { Clock swatch = new Clock(12,59,59); Clock seiko = new Clock(12,59,59); System.out.println(swatch.getHours()); // 12 System.out.println(seiko.getHours()); // 12 swatch.secondElapsed(); System.out.println(swatch.getHours()); // 1 System.out.println(seiko.getHours()); // 12 } }
  • 22. Method Parameters  A method can be defined to accept zero or more parameters  Each parameter in the parameter list is defined by its type and name  The parameters in the method definition are called formal parameters  The values passed to a method when it is invoked are called actual parameters  The name of the method together with the list of its formal parameters is called the signature of the method public void setTime(int h, int m, int s)
  • 23. Method setTime() public void setTime(int h, int m, int s){ if ((s >= 0) && (s < 60) && (m >= 0) && (m < 60) && (h > 0) && (h <= 12)) { hours = h; minutes = m; seconds = s; } // no effect if input is illegal }
  • 24. Lesson 4 – Classes & Objects UNIT D3 - METHOD WRITING DETAILS
  • 25. Variable Scope  Variables may be declared in:  Class – state variables  Method/constructor – local variables (and parameters)  Inner block of a method – also local variables  A variable is recognized throughout the block in which it was defined. This is called the scope of the variable.  Local variables are allocated when the method is entered and freed when the method exits.  The same name may be used in different scopes, and refer to totally different things  If the same name is used in an outer and inner scope, then the inner scope definition “hides” the outer one.
  • 26. The this reference  When appearing inside an instance method, the this keyword denotes a reference to the object that the method is acting upon.  The following are equivalent: public int getHours() { return hours; } public int getHours() { return this.hours; }
  • 27. Using same names for parameters and fields  It is usually bad practice to use the same name for a state variable and a local variable or parameter.  Exception: parameters that correspond exactly to fields public void setTime(int hours, int minutes, int seconds) { if ((seconds >= 0) && (seconds < 60) && (minutes >= 0) && (minutes < 60) && (hours > 0) && (hours <= 12)) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } // no effect if input is illegal }
  • 28. Passing Parameters  When a parameter is passed, a copy of the value is made and assigned to the formal parameter: Clock beritling = new Clock(1,2,3); int lunchHour = 12; breitling.setTime(lunchHour,32,14); hours = lunchHour minutes = 32 seconds = 14
  • 29. Parameters are passed by value Clock c = new Clock(1,2,3); int a= 7; c.funnyGetHour(a); // still 7!! class Clock { // … public void funnyGetHour(int h){ h = hours; } }
  • 30. Passing Object parameters  When an Object is a parameter, only the reference is passed by value. The parameter now is an alias of the object. class XX { // … public void setMidnight(Clock c) { c.setTime(12,0,0); } class YY { // … XX x = new XX(); Clock myClock = new Clock(1,2,3); x.setMidnight(myClock); // 12:0:0
  • 31. Example: A Bank Account Object public BankAccount(long accountNumber) public void deposit(double amount) public void withdraw(double amount) public double getBalance() public void transfer(double amount, BankAccount targetAccount) BankAccount
  • 32. Bank Account - example public class BankAccount { private long accountNumber; private double balance; public BankAccount(long accountNumber){ this.accountNumber = accountNumber; balance = 0; } public double getBalance() { return balance; } // continued in the next slide... }
  • 33. Bank Account - example public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public void transfer(double amount, BankAccount targetAccount){ withdraw(amount); targetAccount.deposit(amount); }
  • 34. Bank Account – usage example BankAccount aliceAcc = new BankAccount(1398723); BankAccount bobAcc = new BankAccount(1978394); aliceAcc.deposit(900); aliceAcc.transfer(700,bobAcc); // Alice’s balance = 200 ; Bob’s balance = 700
  • 35. Constructor and Method Overloading  A class can define several constructors -- several ways to initialize an instance of this class  These constructors differ by the number and/or type of parameters they get.  When we construct an object, the compiler decides which constructor to invoke according to the number and types of the actual arguments  A constructor with no parameters is called the default constructor  Different methods can also use the same name as long as they differ in the number or type of parameters.  When we invoke a method, the compiler decides which method to invoke according to the number and types of the actual arguments
  • 36. Constructor Overloading example public Clock(int h, int m, int s){ hours = h; minutes = m; seconds = s; } public Clock(int h) { this(h, 0 ,0); } public Clock() { this(12); }
  • 37. Lesson 4 – Classes & Objects UNIT D4 - VISIBILITY MODIFIERS
  • 38. Visibility Modifiers  We accomplish encapsulation through the appropriate use of visibility modifiers  Visibility modifiers specify which parts of the program may see and use any particular class/method/field  Information hiding is good!  A modifier is a Java reserved word that specifies particular characteristics of a programming construct  We've used the modifier final to define a constant  Java has three visibility modifiers: public, private, and protected  We will discuss the protected modifier later in the course
  • 39. Visibility Modifiers - Classes  A class can be defined either with the public modifier or without a visibility modifier.  If a class is declared as public it can be used by any other class  If a class is declared without a visibility modifier it has a default visibility. This draws a limit to which other classes can use this class (classes in the same package). We will discuss default visibility later in the course.  Classes that define a new type of objects, that are supposed to be used anywhere, should be declared public.
  • 40. Visibility Modifiers - Members  A member is a field, a method or a constructor of the class.  Members of a class can be declared as private, protected, public or without a visibility modifier:  Members that are declared without a visibility modifier are said to have default visibility. We will discuss default and protected visibility later in the course. private int hours; int hours; public int hours;
  • 41. Public Visibility  Members that are declared as public can be accessed from any class that can access the class of the member  We expose methods that are part of the interface of the class by declaring them as public  Example: the methods getHours(), secondElapsed() and setTime() are part of the interface of class Clock so we define them as public.  We do not want to reveal the internal representation of the object’s data. So we usually do not declare its state variables as public (encapsulation)
  • 42. Private Visibility  A class member that is declared as private, can be accessed only by code that is within the class of this member.  We hide the internal implementation of the class by declaring its state variables and auxiliary methods as private.  Data hiding is essential for encapsulation.
  • 43. Illegal Access - example // Example of illegal access class BankAccountTest { public static void main(String[] args) { BankAccount victim = new BankAccount(2398742); victim.balance = victim.balance - 500; // this will not compile! } } public class BankAccount { private long accountNumber; private double balance; // …
  • 44. Encapsulation not Among Instances of Same Class  Encapsulation is to protect the programmers and is thus between the code of different classes  Sometimes object instances of the same class need to access each other’s “guts” (e.g., for state copying - if we want to create an identical instance of an object we have)  Example:  from within a BankAccount object, any private member of a different BankAccount object can be accessed.
  • 45. Encapsulation - example public void transfer(double amount, BankAccount targetAccount) { withdraw(amount); targetAccount.deposit(amount); } // alternative version (valid, but not so nice) public void transfer(double amount, BankAccount targetAccount) { balance -= amount; targetAccount.balance += amount; }
  • 46. Lesson 4 – Classes & Objects UNIT D5 - API DOCUMENTATION
  • 47. API Documentation  Your classes are often intended to be used by other programmers  Programmers that use your class are not interested in the way it is implemented. They want to use it as a whole and are only interested in what it does and how to use it.  API (Application Programmer Interface) documentation is a description of the interface of the class intended for the application programmer who wants to use it.  To use the class, we need not (and should not) look at the code. All that is needed is the class API.
  • 48. API Documentation  The JDK contains a special tool for the generation of API documentation for your classes, called javadoc.  Any documentation which is part of the interface begins with /** (double asterick) and ends with */  javadoc takes as input Java programs and automatically generates documentation using:  the public/protected method signatures  the documentation comments (enclosed by /** … */).  The output is an HTML file which can be viewed by an internet browser.
  • 49. Clock API Documentation /** * A clock represents a point of time in a 12 * hour period within a precision of seconds. * Its range: 1:00:00 -- 12:59:59. */ public class Clock { private int hours; private int minutes; private int seconds; /** * Constructs a Clock: Sets the clock to the * specified time. */ public Clock(int hours, int minutes, int seconds){ //… }
  • 50. Clock API Documentation – cont. /** * Constructs a Clock: Sets the clock to 12:00:00 */ public Clock(){ this(12,0,0); } /** * Advances this clock by 1 second. */ public void secondElapsed() { //… } //…
  • 51. Javadoc Process .java file .html file javadoc View using a browser
  • 52. Clock javadoc - page 1
  • 53. Clock javadoc - page 2
  • 54. What should you comment?  You should put a documentation comment for the class itself and for any member of the class which is part of its interface.  All public constructors and methods should have documentation comments.  Private methods are not part of the interface of the class, thus javadoc skips them. (But you should still comment them for internal purposes.)  In the rare cases that there are public fields, they should have documentation comments.
  • 55. API Documentation  Remember that documentation comments are written for programmers who use your class as a whole. They should describe only  What the class does,  How to use it.  Documentation comments should not describe how a class is implemented.  Documentation comments should be  Short and descriptive,  Written in a simple language (ENGLISH),  Accurate.  Assume that the reader doesn’t know anything about your class
  • 56. API Documentation Tags  Documentation comments can also include tagged paragraphs that give a standard way to document several features of the interface such as method parameters, return values, etc.  A tagged paragraph begins with the symbol @ followed with a tag keywords. Tags: @see, @author, @version, @param, @return, @exception.  Documentation comments text can include HTML tags.
  • 57. @param tag /** * Changes the current time to hour:minute:second * @param hours The new hour value. * @param minutes The new minutes value. * @param seconds The new seconds value. */ public void setTime(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; }
  • 59. @return /** * Returns the current hour * @return The current hour (between 1 and 12). */ public void getHour() { return hours; }
  • 61. Naming  The names you use for your class and for its public methods are part of the class API.  Good descriptive naming are crucial for a clear API.  General rules about naming:  Follow the Java conventions  Use descriptive names  Do not use abbreviations!  Make names long enough, not unnecessary long  Consist of words in English with no abbreviations  Use a dictionary  Read the style guidelines!
  • 62. Changing the Implementation of a Class  Encapsulation allows us to change an implementation of a class without affecting other parts of the program.  Without encapsulation changes to implementation might “break” the program - many changes  Why would we want to change the implementation?  Different implementations have different tradeoffs (e.g., space conservation, efficiency etc.)  Example: a time instance in the day can be represented by the number of seconds since midnight  Assume we want to change the implementation of the clock - what is involved in the process?
  • 63. Example of new Clock implementation - page 1 /** * A clock represents a point of time in a 12 * hour period within a precision of seconds. * Its range: 01:00:00 -- 12:59:59. */ public class Clock { private static final int SECONDS_IN_12H = 12*60*60; private int secondsFromZero; /** * Constructs a Clock: Sets the clock to the * specified time. */ public Clock(int hours, int minutes, int seconds){ secondsFromZero = ((hours%12) * 3600 + minutes * 60 + seconds); }
  • 64. Example of new Clock implementation - page 2 /** * Constructs a Clock: Sets the clock to 12:00:00 */ public Clock(){ secondsFromZero=0; } /** * Advances this clock by 1 second. */ public void secondElapsed() { secondsFromZero = (secondsFromZero+1) % SECONDS_IN_12H; } //…
  • 65. Example of new Clock implementation - page 3 /** * Returns the current hour * @return The current hour (between 1 and 12). */ public void getHour() { int h = secondsFromZero/3600; return h > 0 ? h : 12 ; } // all the others can be written in the same way
  • 66. Lesson 4 – Classes & Objects UNIT D6 - APPLET METHODS & GRAPHIC OBJECTS
  • 67. Applet Methods  We saw in earlier applets the use the of the paint method to draw the content of the of the applet on the screen.  An applet has several other methods that perform specific duties.  Because the applets are specifically designed to work with web browsers, some particular applet methods are designed around that concept. public void paint(Graphics g)
  • 68. Some Applet Methods  Initializes the applet. Called just after the applet is loaded.  Starts the applet. Called just after the applet is made active.  Stops the applet. Called just after the applet is made inactive.  Destroys the applet. Called when when the browser is exited. public void init() public void start() public void stop() public void destroy()
  • 69. Init, start, stop, and destroy.  The init method is executed once when the applet is first loaded, such as when the browser or the applet viewer initially view the applet.  This is the place to to initialize the applet’s environment and permanent data.  The start/stop methods of an applet are called when the applet becomes active/inactive.  For example, after we use a browser to initially load an applet start is called. When we leave the page, the applet becomes inactive and stop is called. If we return to that page the applet becomes active again and start is called. init start stop destroy
  • 70. Objects with Graphic representation  Many programs are graphic  Many objects in such programs correspond to “graphic objects” on the screen – this is good programming practice.  Such a graphic object will know how to draw itself on the screen
  • 72. The Lineup programs  The LineUp applet, shown in the previous slide shows 4 stick figures of different heights and colors.  It uses a StickFigure class that represents a stick figure of a certain height, color, and location.  The applet creates 4 StickFigure objects, of varying color and random height.  The StickFigure objects are instantiated in the init method of the applet, so they are created once when the applet is loaded.  The paint method of LineUp simply requests that the stick figures draw themselves.
  • 73. StickFigure - 1 import java.awt.*; public class StickFigure { private int baseX; private int baseY; private Color color; private int height; public StickFigure(int center, int bottom, Color shade, int size) { baseX = center; baseY = bottom; color = shade; height = size; }
  • 74. StickFigure - 2 public void draw(Graphics page) { int top = baseY – height; page.setColor(color); //head page.drawOval(baseX-10,top,20,20); //trunk page.drawLine(baseX,top+20,baseX,baseY-30); page.drawLine(baseX,baseY-30,baseX-15,baseY); //legs page.drawLine(baseX,baseY-30,baseX+15,baseY); //arms page.drawLine(baseX,baseY-70,baseX-25,baseY-70); page.drawLine(baseX,baseY-70,baseX+20,baseY-85); }
  • 75. LineUp - code import java.applet.Applet; import java.awt.*; public class LineUp extends Applet { private final int APPLET_WIDTH = 400; private final int APPLET_HEIGHT = 150; private final int HEIGHT_MIN = 100; private final int VARIANCE = 30; private StickFigure figure1, figure2, figure3, figure4;
  • 76. LineUp - code public void init () { int h1, h2, h3, h4; // heights of figures h1 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN; h2 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN; h3 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN; h4 = (int)(Math.random() * VARIANCE) + HEIGHT_MIN; figure1 = new StickFigure(100,150,Color.red,h1); figure2 = new StickFigure(150,150,Color.cyan,h2); figure3 = new StickFigure(200,150,Color.green,h3); figure4 = new StickFigure(250,150,Color.yellow,h4); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); }
  • 77. LineUp - code public void paint (Graphics page){ figure1.draw(page); figure2.draw(page); figure3.draw(page); figure4.draw(page); } }
  • 78. Lesson 4 – Classes & Objects UNIT D7 - STATIC AND AUXILIARY METHODS
  • 79. The Static Modifier  The static modifier can be applied to variables or methods  It associates a variable or method with the class rather than an object  Methods that are declared as static do not act upon any particular object. They just encapsulate a given task, a given algorithm.  We can write a class that is a collection of static methods. Such a class isn’t meant to define new type of objects. It is just used as a library for utilities that are related in some way.
  • 80. Example - a Math Class /** * A library of mathematical methods. */ public class Math { /** * Computes the trigonometric sine of an angle. */ public static double sin(double x) { … } /** * Computes the logarithm of a given number. */ public static double log(double x) { … } // ...
  • 81. Static Variables  A variable that is declared static is associated with the class itself and not with an instance of it.  Static variables are also called class variables.  We use static variables to store information that is not associated with a given object, but is relevant to the class.  We have already seen such usage - constants of a class (final static)
  • 82. Static Variables - Example public class BankAccount { private long accountNumber; private double balance; private static int numberOfAccounts = 0; public BankAccount() { this.accountNumber = ++numberOfAccounts; this.balance = 0; } public static int getNumberOfAccounts { return numberOfAccounts; } }
  • 83. Static Methods and Instance Variables  Static methods:  cannot reference instance variables (e.g. - access instance variable when an object doesn’t exist)  can reference static variables or local variables (within the method)  this has no meaning inside a static method, thus its use inside a static method is not allowed.  Instance methods can access static variables.
  • 84. Division Into Methods  Complicated tasks or tasks that occur often within a class should be wrapped in a method  If you can clearly define the task, you should probably make it a method.  This results in a readable and manageable code  This is very helpful when implementing algorithms, or when we need “helper” methods in classes.
  • 85. Division into methods – interest calculation public class BankAccount { final static int DAYS_IN_YEAR = 365; public void earnDailyInterest(int days){ double rate = 1 + interestRate()/DAYS_IN_YEAR; for(int j=0 ; j<days ; j++) balance *= rate; } private double interestRate() { return (balance>100000) ? 0.06 : 0.05; }
  • 86. Division into Methods – Printing primes public class PrintPrimes { public static void main(String[] args) { for(j = 2 ; j < 1000 ; j++){ if (isPrime(j)) System.out.println(j); } } private static boolean isPrime(int n){ for(int j=2 ; j < n ; j++) if (n%j == 0) return false; return true; } }
  • 87. Lesson 4 – Classes & Objects