0% found this document useful (0 votes)
7 views54 pages

Understanding Class Definitions in Java

This document provides an overview of class definitions in programming, focusing on properties, constructors, and methods. It explains the structure of a class, the role of attributes, and the importance of constructors for object initialization. Additionally, it covers variable scope, lifetime, and the distinction between primitive and object types in Java.

Uploaded by

Nicolás alonso
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)
7 views54 pages

Understanding Class Definitions in Java

This document provides an overview of class definitions in programming, focusing on properties, constructors, and methods. It explains the structure of a class, the role of attributes, and the importance of constructors for object initialization. Additionally, it covers variable scope, lifetime, and the distinction between primitive and object types in Java.

Uploaded by

Nicolás alonso
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

School of Computer Science

Lesson 3: Class definitions

Introduction to Programming
Concepts
 Attributes or properties
 Constructors
 Methods
 Assignment sentences
 Conditional sentences
 Variables and operators
 Unit testing

© C. Luengo Díez 2
Properties, constructors and methods
 Code in most of the classes can be divided into
two parts.

 A smaller outer wrapping which provides the class name.

public class TicketMachine {


// Inner part is omitted
}

 A larger inner part which does all of the work.

© C. Luengo Díez 3
Properties, constructors and methods
public class TicketMachine {
// Inner part is omitted
}

 CANNOT change the order


 You can omit the keyword public

© C. Luengo Díez 4
Properties, constructors and methods
 In the inner part we define:
 The properties or attributes They store data
(values) for each object to use them.
 The constructors They allow each object to be
properly set up when created.
 The methods They implement the object’s behaviour.

 They provide the class its particular features and


behaviour.
© C. Luengo Díez 5
Properties, constructors and methods
There is no pre-established order for them but you have to follow a given
style.

public class ClassName {


Properties or attributes
Constructors
Methods
}

© C. Luengo Díez 6
Properties
public class TicketMachine {
private double price; // the ticket price
private double balance;
private double total;
}

 Each property has its own source code declaration.


 You can use comments:
 One line comments //
 multiline, starting with /* and ending with */

© C. Luengo Díez 7
Properties or attributes
 They are also known as instance variables or fields.

 They are small data spaces inside an object to store values.

 When an object is created it has a reserved space for each


field defined in its class.

ticketMachine1: The ticket price


TicketMachine
The amount of money loaded
price
balance The total amount of money collected
© C. Luengo Díez total by the machine 8
Properties or attributes
 Since they store values that can vary over time they are
called (instance) variables.
Which is the type of the following fields?

private int amount;


private Student delegate;
private Server host;

Which are the names for the following fields?

private boolean alive;


private Person tutor;
private Game game;
© C. Luengo Díez 9
Constructors
 They set up each object so it can be used once created.

 This operation is called initialization.

 They have the same name of the class where they are
defined in, and they do not have a return value.

public TicketMachine (double ticketPrice){


setPrice(ticketPrice);
setBalance(0.0);
setTotal(0.0);
}

© C. Luengo Díez 10
Constructors
ticketMachine1: 6.5 is the value for the ticket price
TicketMachine 0.0 is the value for balance
0.0 is the value for the total
price 6.5
You should explicitly write the initialization code.
balance 0.0 This is a way of self-documenting your code
total 0.0 showing that your objects are initialized and that
you haven’t forgotten to give them a value.

 In Java, if you do not explicitly initialize the properties, they


receive a default value automatically.

int 0
double 0.0
boolean false
String null
© C. Luengo Díez 11
Passing data via parameters (I)
 Both constructors and methods receive data via their parameters.

ticketMachine1:
TicketMachine
price 6.5
balance 0 Assignment
Input data total 0
(parameter) (B)

TicketMachine Additional memory space is created


(A)
(Constructor) when a constructor or method is
running to store the value of
ticketPrice 6.5 parameters and local variables..

© C. Luengo Díez 12
Passing data via parameters (II)
 You have to distinguish between the name of the parameters
inside a method or constructor and the values passed when
that method or constructor is called.

 Names formal parameters

 Values actual parameters


public TicketMachine (double ticketPrice)


t= new TicketMachine(6.5);
Formal parameter

Actual parameter
© C. Luengo Díez 13
Objects as parameters
 Objects can be used as parameters for other objects’ methods.

 If a method requires a parameter to be an object (actually a


reference to an object), the name of the class of the expected
object is used as the parameter type in the method’s
signature.
public void punch(Square square)

public void requestGroupChange(Form request)

© C. Luengo Díez 14
Variable scope
 A variable scope defines the source code section in
which that variable can be used.
 A formal parameter is only available inside the method
or constructor where it has been declared.

 The scope for an attribute is the whole class, i.e., it can


be accessed from everywhere inside the class.

© C. Luengo Díez 15
Variable lifetime
 A variable’s lifetime describes for how long it will exist
before being removed from memory.

 The lifetime for a parameter is limited to the running


time of the method or constructor where it’s been declared.

 Once the method or constructor has finished, the formal parameters


disappear, the space they used is released and their values are
lost.

 The lifetime for a property is the same as that of the object


to which belongs.

© C. Luengo Díez 16
Exercise
 Which is the class for the following constructor?

public Dog (String name)

 How many parameters does this constructor have? Which are


their types?

public Book (String title, double price)

 Which attributes (both names and types) could the Book class
have?

© C. Luengo Díez 17
Assignment
 The assignment sentence copies the value at the right of
the = sign into the variable in the left side.

price = ticketPrice;

Variable
Expression
Operator

Rule The type of the assigned expression must be compatible with the variable to which it’s
assigned.

The same applies to the relationship between formal and


actual parameters.
© C. Luengo Díez 18
Primitive types vs object types
 In Java, primitive types are those that are not objects
Integer numbers byte (8 bits) [-128 to 127]
short (16 bits) [-32768 to 32767]
int (32 bits) [-2147483648 to 2147483647]
long (64 bits) [-9223372036854775808 to
9223372036854775807 ]
Floating-point float +1.40e-45f +3.4028235e38f
numbers double +4.9e-324 +1.7976931348623157e308
Other types char (16 bits Unicode)
boolean (true or false)

 Object types are those defined using classes. Some of them


are defined by the system (i.e., String)

19
© C. Luengo Díez
Using primitive data types
 Given the following attribute declaration
private byte age;
private short shortNumber;
private float floatNumber;
private double doubleNumber;

Valid assignments Invalid assignments

age = 127; age = 128;


shortNumber = -32768; shortNumber = -32769;
floatNumber = 23.345f; floatNumber = 23.345;
doubleNumber = 23.345; doubleNumber = 23.345u;
doubleNumber = 23.345d;
doubleNumber = 23.345f;

20
© C. Luengo Díez
Primitive types vs object types

Primitive type Object type

int x; x Dog p; p

The stored value is an integer. The stored value is


For instance: a reference.

12
Name for a
memory zone
© C. Luengo Díez 21
Primitive types vs object types
Object type Class name

Person p1; p1

p1 = new Person(); p1:


Person
p1

Primitive type int age; age

age = 18; age 18

© C. Luengo Díez 22
Primitive types vs object types
Person p1; Person p2; p2

p1 = new Person();
p2 = p1;
p1:
p1 Person
p2

int a = 32; int b; b

a 32 b = a; b 32

© C. Luengo Díez 23
Methods (I)
 Methods have two different parts
 Header
// This method returns the ticket price
public double getPrice()

 Body enclosed between curly brackets {}


{
return price;
}

 It contains declarations and sentences.


 A set of declarations and sentences between curly brackets is a
© C. Luengo Díez
block. 24
Methods (II)
 There are important differences between the signature of
constructors and methods.
public TicketMachine(double ticketPrice)
public double getPrice()

Which differences do you notice?

Rule Constructors do not have a return type.

© C. Luengo Díez 25
Methods (III)
 This sentence in the previous example:
return price;

 is a return sentence. It is responsible for returning a value (a


double in this case) compatible with the return type of the
method (also double this time).

// This method returns the ticket


// price
The return sentence is
public double getPrice() { always the last
return price;
executed one . No
}
more sentences are
executed after that.
© C. Luengo Díez 26
Accessor methods
 They provide information on the object’s status
// This method returns the ticket price
public double getPrice(){
return price;
}

Convention
Every method returning the value of an attribute must start
with the get prefix
Those methods returning the value of a boolean attribute
must start with the is prefix
.
© C. Luengo Díez 27
Mutator methods
 They change the object’s status
// Sets a new balance
public void setBalance(double amount){
balance = balance + amount;
}

 Compound assignment operator balance += amount ;


Convention
Every method that changes the value of an attribute should start with the set
prefix.

© C. Luengo Díez 28
Printing from methods
The + sign is the string
 Given this method concatenation operator. It is
used to produce a single string.

// Print a ticket and reduce balance to zero


public void printTicket() {
[Link] (“ Ticket”);
[Link] (“ Price:” + price);
[Link]();
balance = 0.0;
}

 The method [Link] prints the parameter it


receives to the screen (text terminal).
© C. Luengo Díez 29
The conditional statement
 This version of the method does not check its parameter
public void insertMoney(int amount) {
balance = balance + amount;
} Comparison
operator

 Now, we check that the amount makes sense

public void insertMoney(int amount){


if (amount > 0){
balance = balance + amount;
}
}

© C. Luengo Díez 30
The conditional statement
 Also called if sentence

 It provides a way to perform one of two possible actions depending on the


resulting value of a given test.
if (test returning a true or false result) {
The test returned true, perform this action.
}
else {
The test returned false, perform this other action.
}

 A boolean expression or condition, i.e., something with only two possible


values (true or false).

© C. Luengo Díez 31
Some examples
if sentence if-else sentence if else-if else sentence
if (condition) { if (condition) {
if (condition) {
statements statements
statements
} else { } else if (condition) {
}
statements statements
} } else {
statements
}
if (score >= 90) {
grade = “A";
} else if (score >= 80) {
grade = “B";
} else if (score >= 70) {
grade = “C";
} else {
grade = “F";
}
32
© C. Luengo Díez
Primitive types
x = y;
Assignment
x = 12; x 12
y = 14; y 14 x 14
Comparison
if (x == y)
...
Parameter passing 9
void f (int x) copy int y = 9;
{ x = y f(y);
... [Link](y);
x = 0;
}
Formal parameter Actual parameter
© C. Luengo Díez 33
Object types
Dog dog1; dog1
Dog dog2; dog2

dog1 = new Dog(); dog2 = new Dog();

:Dog :Dog

name “Rufus” name “Fido”

dog1 dog2
© C. Luengo Díez 34
Object types
:Dog :Dog
Assignment
name “Rufus” name “Fido”

dog1 dog2

:Dog :Dog

name “Rufus” name “Fido”


dog1 = dog2

© C. Luengo Díez 35
dog1 dog2
Object types
:Dog :Dog
Comparison
name “Rufus” name “Fido”

if (dog1 == dog2)

dog1 dog2
false
:Dog :Dog

name “Rufus” name “Fido”

true
36
© C. Luengo Díez dog1 dog2
Object types
Parameter passing

public void feed (Dog p){


...
p = null;
}

copy
p = tobi
public void dogsHome()
{
Dog tobi = new Dog();
feed(tobi);
...
}
37
© C. Luengo Díez
Local variables
 A local variable is a variable declared and used inside a method.
 Its scope is limited to the code inside the method.
 Its lifetime is limited to the method’s running time.
/* compute the difference between the balance
* and the ticket price
*/
public int refundBalance() {
double difference;
difference = balance - price;
balance = 0.0;
return difference;
}

© C. Luengo Díez 38
Summary: properties, parameters and
local variables (I)
 There are three kinds of variables.
 Properties or attributes
 They are defined outside methods and constructors.
 They are used to store data needed during the whole life of the
object. Their lifetime expires when the object is destroyed.
 The scope of fields is the whole class. That is, they can be used
from any method or constructor of the class.
 They cannot be accessed from outside the class if they are
defined as private.

© C. Luengo Díez 39
Summary: properties, parameters and
local variables (II)
 Parameters
 Formal parameters do exist during a constructor or method
running time. Their values are lost between calls.

 Formal parameters are defined in a constructor or method’s


signature. They are initialized with the values of the actual
parameters used during the call.

 Formal parameters scope is limited to the method or


constructor where they are defined.

© C. Luengo Díez 40
Summary: properties, parameters and
local variables (III)
 Local variables
 They are declared within the body of a method or constructor.

 They are used inside the body. They must be initialized


before being used, they do not have any default value.

 They exist during the running time of the method or


constructor. Their values are lost between calls.

 Their scope is limited to the block where they are declared.


They cannot be accessed from outside that block.

© C. Luengo Díez 41
Logical operators
 They work on boolean values (true or false) and produce as a
result a new boolean value. a b a && b a || b !a !b
Logical operators && (and) T T T T F F
|| (or) T F F T F T
! (not)
F T F T T F
F T F F T T

 The expression a && b is true if both a and b are true and false
otherwise.

 The expression a || b is false is both a and b are false and true


otherwise.

 The expression !a is true when a is false and vice versa.


42
© C. Luengo Díez
Relational operators
Operator Name Example meaning
< less than a<b a is less than b
> Greater than a>b a is greather than b
== Equal to a==b a is equal to b
!= Not equal to a!=b a is not equal to b
<= Less than or equal to a<=b a is less than or
equal to b

>= Greater than or equal to a>=b a is greater than or


equal to b

43
© C. Luengo Díez
Exercise
 What does this method do?
public void setValue(int newValue){
if ((newValue >= 0) && (newValue < 60))
value = newValue;
}
 What does it happen if you use these conditions instead of the original
one?
if ((newValue > 0) && (newValue < 60))
if ((newValue > 0) || (newValue < 60))
 Which of the following expressions are true?
! (4 < 5) (2 > 2) || (4 ==4) && (1 < 0)
! false (34 != 33) && ! false
(2 > 2) || ((4 ==4) && (1 < 0)) (4 <= 8) && (8 > 5) || (3 < 2)
44
© C. Luengo Díez
String concatenation
 The addition operator (+) has different meanings
depending on the type of the operands.

42 + 12 54
“Java” + “with BlueJ” “Javawith BlueJ”
“answer: “ + 27 “answer: 27”
return “0” + value “08” if value contains an 8
return “” + value “8” if value contains an 8

45
© C. Luengo Díez
Division and modulo operators
 The modulo operator (%) computes the remainder for
an integer division.
 The slash operator (/) computes the quotient for an
integer division.
27 / 4 6
27 % 4 3
8%3 2

public void increment(){ What does this method do?


value = (value + 1) % 60;
} Replace this using an if
sentence.
46
© C. Luengo Díez
Operators (main ones) precedence
 Listed below, from highest to lowest precedence
Operators Precedence If several appear …
postfix expr++ expr--
unary ++expr --expr +expr -expr !
multiplicative * / % Left to right
additive + - Left to right
relational < > <= >=
equality == !=
logical AND && Left to right
logical OR || Left to right
ternary ? :
assignment = += -= *= /= %= Right to left
47
© C. Luengo Díez
The this keyword
 Sometimes the same name is used to refer both a parameter
and an attribute. We use this to disambiguate them.
public class Message {
private String from;
private String to;
private String text;

public Message (String from, String to, String text) {


[Link] = from;
[Link] = to;
[Link] = text;
}
}

48
© C. Luengo Díez
The this keyword
 this refers to the current object:
[Link] = from;

 This sentence actually means:


Attribute with name “from” = parameter with name “from”;

 If a given name perfectly describes something, we should use it


both for parameters and attributes and rely on this to solve the
ambiguity.

49
© C. Luengo Díez
Error handling
 At the beginning, most of the errors are syntax errors.
 The IDE highlights them in your code.
 Later, most common errors are logic errors.
 IDE does not help to find them.
 They are the well-known “bugs”.

 Some logic errors are not immediately obvious.


 Commercial software sometimes (many times) has bugs.

© C. Luengo Díez 50
“Hand made” unit testing with BlueJ
 You can create objects for each class.
 You can call each individual method.
 You can use the Inspect function to check the status of the
object.

Making good tests is a creative process,…


However, testing is time-consuming and repetitive.
(That’s why they are not “hand made”).

51
© C. Luengo Díez
Unit testing
 Special classes are developed only to make the tests
(they contain test methods).

 Those classes are known as unit tests because they are used
to check/test individual classes.

 Each “common” class from the project is associated to a


test class.

© C. Luengo Díez 52
Unit testing with JUnit
 JUnit is a testing framework for Java.
 A JUnit test class contains:
 Source code to run the tests on a given class.

 Source code to check the tests were OK by means of assertions.

 An assertion is an expression establishing a condition which


is assumed to be true. If it is false, it means the assertion
failed and, thus, there is a bug in the program.

© C. Luengo Díez 53
Testing with JUnit
@Test
public void insertMoney(){
TicketMachine ticketMa1 = new TicketMachine(400);
[Link](900);
assertEquals(900, [Link](), 0.1);
}

@Test
public void printTicketRightBalance() {
TicketMachine ticketMa1 = new TicketMachine(600);
[Link](600);
[Link]();
assertEquals(0, [Link](), 0.1);
}

© C. Luengo Díez 54

You might also like