Transcript OOPx

Data Structures
and Algorithms
revision
Objects
• An Object is “some data/attributes”,
• and a set of ways (methods) of
changing/accessing the data.
Classes vs Objects
• You have a single class e.g. Person.
• You can make many objects of the type Person.
Person p1 = Person();
// the default object
Person p2 = Person(“John”, 99);
// makes a person called p2 with the values John with age 99
Person p3 = p2;
//makes a person p3 ….
• All 3 Person objects belong to the Person class
CSCU9A3 - Autumn 2015
3
Analogy: In an Office (before computers)
1.
2.
3.
4.
Imagine you work in an office (bank).
You have a paper form with blanks in
(e.g. name, address, salary)
When somebody opens a bank account – you
photocopy the form and fill in their
individual details.
5. The blank form is like a Class – there is only
one blank form (THE MASTER COPY).
6. Each photocopied form is like an Object.
CSCU9A3 - Autumn 2015
4
One class, many objects
• A class is a template for making objects.
• E.g.
PERSON CLASS
Int
Age
String
Name
P2
P1
PERSON
OBJECT
Int
Age
String
Name
PERSON
OBJECT
55
Int
Age
98
dave
String
Name
james
DANGER OF PUBLIC
• If your data is public – it can be changed to
anything
PERSON
CLASS
public
int
age
public
string
Name
Person p1 = new Person(“dave”,55);
PERSON
OBJECT
int
age
-100
string
Name
“dave”
P1.age = -100; //SHOULD NOT HAPPEN
Private data
• If your data is private– you are forces to use
the set methods to change it.
PERSON
CLASS
private
Int
age
private
string
Name
Person p1 = new Person(“dave”,55);
p1.age = -100; //SHOULD CANNOT HAPPEN
PERSON
OBJECT
int
Age
55
String
Name
“dave”
We use a setAge method
setAge method
public void setAge(int a) {
if (a > 0) {
this.age = a;
} else {
System.out.println("age not
set, cannot be negative");
}
}
Overloaded Methods
• A class can have a number of methods with
the same name, but different parameters
• Example: println methods, one for each different
type of thing you might want to print:
• public void println(int output)
• public void println(double output)
• public void println(String output)
CSCU9A3 - Autumn 2015
9
Overloaded Methods
• This solve the problem of having to explicitly
tell the program which method:
• public void printlnINT(int output)
• public void printlnDOUBLE(double output)
• public void printlnSTRING(String output)
CSCU9A3 - Autumn 2015
10
Encapsulation
1. Encapsulation means we do not need to
know the details of how the data is stored.
2. You just need to know how to use it.
3. This is sometimes called “data hiding”
4. We do not want to expose the internal
workings of out class – but have an agreed
set of methods by which we communicate
with other classes.
e.g. counter class
•
•
•
•
A counter class with method
Increment (adds one to the count)
Reset (sets the count to zero)
getCount (give the current number)
• (DO AN EXAMPLE WITH THE CLASS)
• This is the interface of the class – it is just the
methods you can see (and the constructor)
Encapsulation - example
• A counter class with methods
• Increment and getCount.
• Could store an integer, which is incremented
by one each time the counter is pressed.
• Could store a string “1111111”, and append
“1” each time. The length represents the
count.
• Could store a number 1000, and multiply by
10 each time we press counter. The count
would just be log of the number.
Syntax 3.1 Instance Variable Declaration
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Accessing Instance Variables
• The count method advances the counter value by 1:
public void count()
{
value = value + 1;
}
• The getValue method returns the current value:
public int getValue()
{
return value;
}
• Private instance variables can only be accessed by methods of the same class
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Instance Variables
1. Encapsulation is the process of hiding object data and providing methods for data access
2. To encapsulate data, declare instance variables as private and declare public methods
that access the variables
3. Encapsulation allows a programmer to use a class without having to know its
implementation
4. Information hiding makes it simpler for the implementor of a class to locate errors and
change implementations
5. Protects your data (get/set methods accessor/mutator methods) from others and from
yourself!!!
6. How else could the class counter be implemented instead of using int ???? (float,
string…)
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Equals (==) for primitive data types
• When comparing primitive data types
– int
– boolean
– float
– double
– char, …
• USE x == y
• NOT x=y (means x becomes the value y)
Equals with objects
• Person p1 = new person(“John”, 55);
• Person p2 = new person(“John”, 55);
• == compares memory address!!!
• Need to use .equals
•
•
•
•
String name1 = “John”;
String name2 = “John”;
name1==name2;// give False
name1.equals(name2); // gives True
Steps to check equality
• 1/ is the object null
• 2/ is the object the same type as you want
e.g. Person, or Percent or Thermometer..
• 3/ now check each of the relevant fields for
equality. (usually all fields)
Example Percent
public boolean equals(Object object) {
if (object == null) {
return false;
} else if (!(object instanceof Percent )) {
return false;
} else {
Percent percent = (Percent ) object;
return this.percent ==
percent.getPercent();
}
}
Static vs non-Static
1. Static variables are the same for every
instance of a class
2. Non-Static variables are different for each
instance of a class
3. E.g. we all have an individual blood pressure
(e.g. 140 over 100 mmHg) non-static
4. But the normal for all of us is 120 over 80
mmHg.
5. What about height, weight and indicators of
obesity as body mass index.
CSCU9A3 - Autumn 2015
21
Object References
• Object reference: describes the location of an object
• The new operator returns a reference to a new object:
Rectangle box = new Rectangle();
• Multiple object variables can refer to the same object:
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
• Primitive type variables ≠ object variables
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Object Variables and Number Variables
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Object Variables and Number Variables
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Inheritance
• Means you can use the methods of the super
class.
• This saves you time writing more java which is
common to a set of classes.
• The common methods and data attributes can
abstracted out as a super class.
Inheritance e.g. 1
• E.g. in the lecture/tutorial we looked at
vehicles.
• All vehicles (car, coach, train) have a
weight/color/passengerCapacity/fuelType.
• Things specific to the subclass can be stored
only in that class e.g. for coach
• doubleDecker = True
• hasToilet = False
Inheritance e.g. 2
• If you are storing information about people, there
are commonalities that all people have
• E.g. name, nationality, height, date of birth.
• For different people you store different information
• E.g. Professor class extends Person
• String areaOfExpertize = “blackholes”;
• String Chair = “Lucasian ”;
• String university = “Cambridge”;
• Int numberBooksPublished = 23;
Syntax 9.1 Inheritance
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Overriding Methods
• Example: deposit and withdraw methods of the CheckingAccount class override
the deposit and withdraw methods of the BankAccount class to handle transaction
fees:
public class BankAccount
{
. . .
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public double getBalance() { . . . }
}
public class CheckingAccount extends BankAccount
{
. . .
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public void deductFees() { . . . }
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Overriding Methods
• A subclass method overrides a superclass method if it has the same name and parameter
types as a superclass method
• When such a method is applied to a subclass object, the overriding method is
executed
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Overriding Methods
• Use the super reserved word to call a method of the superclass:
public class CheckingAccount extends BankAccount
{
public void deposit(double amount)
{
transactionCount++;
// Now add amount to balance
super.deposit
}
}
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Syntax 9.2 Calling a Superclass Method
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley &
Sons. All rights reserved.
Overriding methods.
•
•
•
•
•
•
•
The subclass may override superclass methods.
We do not want this to happen in some cases
E.g. getAge
To stop overriding say
final getAge
To force overriding say
abstact getAge