Upload
erick-foster
View
224
Download
2
Embed Size (px)
Citation preview
1
Programming Week 2
2
Inheritance
Basic Java Language Section
3
Relationships between objects
Sometimes the behaviour and attributes of one class are a superset of anotherFor instance sciencefictionHero may be a superset of Hero with added behaviour such as laser_attack and extra attributes such as the number of batteries for the laser. It would be nice to be able to say sciencefictionHero is a kind of Hero but with specific additions to make it a sciencefictionHero
4
Inheritance, Subclasses and Superclasses
We can inherit the attributes and behaviour (methods) from one class when we create another class SciencefictionHero is subclass of Hero –
more specialised Hero is superclass of SciencefictionHero –
more generalised
The SciencefictionHero class can have additional behaviours and attributes
5
Inheritanceclass SciencefictionHero extends Hero
{int laser_batteries;void laser_attack()
{ laser_batteries = laser_batteries -1;}
}
Lecturer automatically has the attributes and methods Hero has…
6
Inheritance Diagram
We can illustrate the relationship between sciencefictionHero and Hero in a diagram
Hero
SciencefictionHero
7
Inheritance Overriding
Sometimes the superclass has behaviour which is not quite what we want in our subclass. For instance it may be the case that we want a dragon will roar when it takes_damage.. But monster does not do thisA subclass may have methods which override inherited methods of the same name in the superclassWe can call the superclass to perform the overridden behaviour if we want using the word super to refer to the super class…
8
Object oriented concepts
Inheritanceclass Dragon extends Monster
{
void take_damage()
{
roar();
super.take_damage();
}
}
This overrides the take_damage method
defined in Monster
As part of the new behaviour
take_damage calls the take_damage in
Monster to reduce its health
9
Inheritance and Overriding Examplesnotty = new Monster()
fang = new Dragon()
snotty.take_damage()
fang.take_damage()
fang.take_damage(200)
calls the take damage method in
Monster
calls the take damage method in
Dragon
calls the take damage method in
Monster
10
Attributes, Variables and Instances
Basic Java Language Section
11
Variables and Attributes
For the following discussion the word variable is used but the same applies to attributes...
Like methods and classes, they need names
If it is assigned a new value using = the previous value is overwritten
Variables also need to have a type. This tells Java what sort of value the variable can hold and how much memory to give it
Variables must be declared before they can be used
12
Attributes, Variables, Types and Declarations
A variable or attribute can store a single value.The only difference between a variable and an attribute is where it is createdAttributes are created in the class definition, but outside any methodVariables are created inside a method body
13
Variable or Attribute?
class Monster{int health=10;void take_damage()
{int temporary=10;}
}
health is an attribute because it is not declared inside a
method
temporary is declared inside a
method and therefore is a
variable
14
Simple Variables and Instances in Java
A simple variable such as an int always has a value and a name;In the computer some memory is reserved to store the contents of aif a is used just before a = it can be modifiedif a is used anywhere else its contents are fetched
15
Simple VariablesFirst the result for the right hand side is calculated... in
this case 10
first the current value for a found – which is 10
int a;
a=5+5;
a=a+1;
secondly the result is places into the memory reserved
for a. Any previous value in a is lost
second the result of 10 + 1 is calculated
finally the result of the right hand side is put into the memory reserved
for a
16
More things to do with simple variables
you can put a new value inside it using = you can check for equality == and inequality !=for numbers you can also use less than< less than or equal <= greater than > greater than or equal>= + - / *
17
Instances
Unlike simple variables when you declare an instance of a class memory is NOT automatically reservedYou have to create a new instance using new and then make the variable point at the instance
Monster m = new Monster();
18
Problems with instance variables
However declaring does not provide a value to the variable or attribute
Dragon gorkon;
Using a variable before it is initialised can lead to the dreaded NULL pointer exception
gorkon.take_damage();
gorkon does not yet hold an instance of the Dragon class
and cannot yet be used
BANG!!!
19
Initialising Instance variables
When you declare a variable you can also initialise it.
Dragon sarg=new Dragon();
The new instance is sarg assigned to the variable
sarg and is ready to send message to
new Dragon() creates an
instance of the Dragon class and calls the constructor
20
Types and Declarations
Basic Java Language Section
21
Declarations
Before using a variable or attribute it must be declared.Declaring a variable tells the computer several things: The variables name What type of thing the variable will store Optionally an initial value for the variable
int health;Name of variable
Type of variable (will store whole numbers only)
22
Types
The type of the variable tells the computer how much memory is required to store the variable and what type of thing it will storePutting the wrong type of thing into a variable will cause problems
int health;health= 10.4;
Health can only store whole numbers
10.4 is not a whole number
23
Standard (simple) Typesint 32 bit whole number e.g. –234 or 45long 64 bit whole numberfloat 32 bit real number –234.6 or 56.7double 64 bit real numberboolean true or false (if statements and loops)char character such as ‘a’ or ‘z’ (case sensitive)void nothing!!!! (used in the return type of a method)Note none of these are classes!
24
Simple Types int and long
store whole numbers onlylong allows larger numbers to be stored but takes up more memory and is slower to calculate int is 32 bits long is 64 bits
operations include + - / * (multiply)comparisons all generate a boolean == (equals) != (not equals) < <= > >=
25
int operations and comparisons
int a=0;boolean b;a=a+10;b=a==11;
b is false because we ask if a is equal to 11 but a has the value 10
26
Simple Types float and double
store fractional numbers such as 10.5 or 10.0double allows larger numbers to be stored but takes up more memory and is slower to calculate float is 32 bits double is 64 bits
Not always accurate slower than int or longoperations include + - / * (multiply)comparisons all generate a boolean == (equals) != (not equals) < <= > >=
27
Simple Types boolean
only stores the value true or falsefast to calculate and uses little memoryoperations include && || ! ^ (explained on next slides)comparisons all generate a boolean == (equals) != (not equals) cannot use < <= > >= to compare
booleans
28
Combining booleans &&
You can not do maths on booleans but you can combine two booleans into a single valueFor instance AND is && true && true is true true && false is false false && true is false false && false is false
&& is only true if both sides are true
29
&&
a=10;boolean b;b=a==10 && a== 11;
a==10 is truea==11 is falseso we havetrue && false which is falseso b will have the value false
30
Combining booleans ||
For instance OR is || true || true is true true || false is true false || true is true false || false is false
Or is only false if both sides are false
31
||
a=10;boolean b;b=a==10 || a== 11;
a==10 is truea==11 is falseso we havetrue || false which is trueso b will have the value true
32
Combining booleans ^
For instance XOR is ^ true ^ true is false true ^ false is true false ^ true is true false ^ false is false
XOr is true if both sides are different
33
^
a=10;boolean b;b=a==10 ^ a== 11;
a==10 is truea==11 is falseso we havetrue ^ false which is trueso b will have the value true
34
Combining booleans !
For instance NOT is ! !true is false !false is true
! is special because it does not really combine to booleans it just returns the opposite value to the boolean it is in front of
35
a=10;boolean b;b=a==10b=!b;
a==10 is trueso b will have the value truebut b=!b makes b become false;
!
36
Simple Types char
stores a single character such as ‘a’ or ‘A’ onlyno operations are permitted on charscomparisons all generate a boolean == (equals) != (not equals) < <= > >=
37
Java will automatically convert between a limited range of types An int can be converted into a float Numbers can be converted into
strings
float Health;Health=10;
Health can store any decimal number
10 Is a whole number it is automatically converted into the decimal equivalent
10.0
Automatic Type Conversion
38
Manual type ConversionWe can force Java to perform some type conversions by using the type we want to convert into surrounded by brackets. This is called a type cast
int i=0;double d=10.1;i=(int)d;
In this case Java will round the double down to 10.0 and convert the result into 10 and put it in i
39
Why Types Matter
You may be tempted to always use floats. However, floats are slower to process than ints floats an not always accurate floats take up more memory than
ints
=> Use the simplest representation that you can
40
Types – Type Mismatch
int health=10;
if (health==“hello”)
{
scream_and_die();
}
Previously we declared health as a
int (I.e. stores numbers)
But here we try to compare it to
something which is NOT a number
“hello” is a String of characters
Type mismatch
41
Return Types
Basic Java Language Section
42
Return types
Many methods return information, for instance new returns an instance of an object.We can make our own methods return a single object or single simple type.The return type is part of the declaration of the methodConstructors and destructors cannot return anything
43
Return
You can use the return type as if it was the result of a calculation:
int get_bullets(){return bullets;}
Hero james=new Hero();int count = james.get_bullets();
return exits the method immediately
with a copy of the value on its right
hand sidethis value returned cannot be modified
by the caller but can be used in
calculations or copied into a
variable/attribute
44
Returning nothingIf you don’t want to return anything you declare the method as returning voidYou can use return by itself to exit the method immediately
public void shoot(){
return;
}
45
Brackets
Basic Java Language Section
46
Deciding the order of Calculations using brackets
complex maths or combining booleans can result in different values depending upon the order the parts of the line are calculated in.
int a= 10 * 2 + 7;
if 2 +7 is calculated first the result is 9 * 10 which is 90if 10 * 2 is calculated first the result is 27using brackets we can make the order or calculation explicit
47
BracketsThe inner brackets are calculated first so
int a= ( 10 * 2 ) + 7;The result is 10 * 2 is performed first and then 7 added
int a= 10 * ( 2 + 7 );The result is 2 + 7 is performed first and then multiplied by 10
48
The Scope of Declarations
Basic Java Language Section
49
Scope
Java is structured into blocks Where (in which block) you declare a
variable determines which other parts of your program can access it. This is the scope of the variable
A variable can always be accessed within the block is it declared and any blocks nested inside that block
50
Scope - Attributes
bullets is an attribute and is available to all methods in the
class it is declared in
number is declared inside
set_bullets and is therefore available inside set_bullets
bullets is an attribute and is public and is available via the h
instance
The Attributes of a instance are available to anyone who has an instance of the object if the attributes are publicAttributes can be accessed by all methods inside the class regardless of how they are declared
class Hero{public bullets;void set_bullets(int number)
{bullets=number;}
}Hero h=new Hero();h.bullets=10;
51
Scope - ParametersA parameter is only available to the method it is declared in. It cannot even be accessed from other methods in the same class
class Hero{int bullets=0;void set_bullets(int number){bullets=number;}void wrong(){bullets=number;}}
bullets is an attribute and can be accessed
from here
number is declared in another method
and cannot be accessed outside it
52
Scope - VariablesVariables are declared inside the body of a method and are only accessible inside the methodThey are also only accessible below where they are declared
void doit(){a=10;int a=0;a=4;}
illegal a is used before it is
declared
legal a is used before it is
declared
53
Scope - Nesting
A variable can always be accessed within the block is it declared and any blocks nested inside that block
{int a;
{a=10;}
}
no problem a is declared in the block surrounding the block
it is used in.
54
Scope - Nesting
A variable can not be accessed outside the block it is declared in
{{int a;}
a=10;}
a is only available within the grey block and is not accessible
outside the } it is defined in
55
Scope - Sequence
A variable can not be accessed outside the block it is declared in
{int a;}{a=10;}
a is a variable and cannot be
accessed outside the block it is declared in
56
How Variables Work
Methods are executed line by line. As execution comes to a declaration the variable is created and initialisedEach time execution leaves the block a any variables declared inside that block are destroyed
57
Variables – entering and leaving the block
void doit(){int a=10;a=a+1;}
doit();doit();
a is created here and initialised each time the block is entered
when the block (in this case a method) it is declared in is
exited a is destroyed
a is modified here inside the block it is
declared