Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Programming Week 2 2 Inheritance Basic Java Language Section.

Similar presentations


Presentation on theme: "1 Programming Week 2 2 Inheritance Basic Java Language Section."— Presentation transcript:

1

2 1 Programming Week 2

3 2 Inheritance Basic Java Language Section

4 3 Relationships between objects Sometimes the behaviour and attributes of one class are a superset of another For 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

5 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

6 5 Inheritance class SciencefictionHero extends Hero { int laser_batteries; void laser_attack() { laser_batteries = laser_batteries -1; } Lecturer automatically has the attributes and methods Hero has…

7 6 Inheritance Diagram We can illustrate the relationship between sciencefictionHero and Hero in a diagram Hero SciencefictionHero

8 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 this A subclass may have methods which override inherited methods of the same name in the superclass We can call the superclass to perform the overridden behaviour if we want using the word super to refer to the super class…

9 8 Object oriented concepts Inheritance class 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

10 9 Inheritance and Overriding Example snotty = 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

11 10 Attributes, Variables and Instances Basic Java Language Section

12 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

13 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 created Attributes are created in the class definition, but outside any method Variables are created inside a method body

14 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

15 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 a if a is used just before a = it can be modified if a is used anywhere else its contents are fetched

16 15 Simple Variables First 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

17 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>= + - / *

18 17 Instances Unlike simple variables when you declare an instance of a class memory is NOT automatically reserved You have to create a new instance using new and then make the variable point at the instance Monster m = new Monster();

19 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!!!

20 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

21 20 Types and Declarations Basic Java Language Section

22 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)

23 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 store Putting 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

24 23 Standard (simple) Types int 32 bit whole number e.g. –234 or 45 long 64 bit whole number float 32 bit real number –234.6 or 56.7 double 64 bit real number boolean 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!

25 24 Simple Types int and long store whole numbers only long 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) >=

26 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

27 26 Simple Types float and double store fractional numbers such as 10.5 or 10.0 double 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 long operations include + - / * (multiply) comparisons all generate a boolean == (equals) != (not equals) >=

28 27 Simple Types boolean only stores the value true or false fast to calculate and uses little memory operations include && || ! ^ (explained on next slides) comparisons all generate a boolean == (equals) != (not equals) cannot use >= to compare booleans

29 28 Combining booleans && You can not do maths on booleans but you can combine two booleans into a single value For 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

30 29 && a=10; boolean b; b=a==10 && a== 11; a==10 is true a==11 is false so we have true && false which is false so b will have the value false

31 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

32 31 || a=10; boolean b; b=a==10 || a== 11; a==10 is true a==11 is false so we have true || false which is true so b will have the value true

33 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

34 33 ^ a=10; boolean b; b=a==10 ^ a== 11; a==10 is true a==11 is false so we have true ^ false which is true so b will have the value true

35 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

36 35 a=10; boolean b; b=a==10 b=!b; a==10 is true so b will have the value true but b=!b makes b become false; !

37 36 Simple Types char stores a single character such as ‘a’ or ‘A’ only no operations are permitted on chars comparisons all generate a boolean == (equals) != (not equals) >=

38 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

39 38 Manual type Conversion We 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

40 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

41 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

42 41 Return Types Basic Java Language Section

43 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 method Constructors and destructors cannot return anything

44 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 side this value returned cannot be modified by the caller but can be used in calculations or copied into a variable/attribute

45 44 Returning nothing If you don’t want to return anything you declare the method as returning void You can use return by itself to exit the method immediately public void shoot() { return; }

46 45 Brackets Basic Java Language Section

47 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 90 if 10 * 2 is calculated first the result is 27 using brackets we can make the order or calculation explicit

48 47 Brackets The 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

49 48 The Scope of Declarations Basic Java Language Section

50 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

51 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 public Attributes 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;

52 51 Scope - Parameters A 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

53 52 Scope - Variables Variables are declared inside the body of a method and are only accessible inside the method They 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

54 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.

55 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

56 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

57 56 How Variables Work Methods are executed line by line. As execution comes to a declaration the variable is created and initialised Each time execution leaves the block a any variables declared inside that block are destroyed

58 57 Variables – entering and leaving the block void doit() { int a=10; a=a+1; } 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


Download ppt "1 Programming Week 2 2 Inheritance Basic Java Language Section."

Similar presentations


Ads by Google