1 Programming Week 2 2 Inheritance Basic Java Language Section.

Slides:



Advertisements
Similar presentations
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Advertisements

© The McGraw-Hill Companies, 2006 Chapter 8 Extending classes with inheritance.
CS 106 Introduction to Computer Science I 01 / 30 / 2008 Instructor: Michael Eckmann.
1 Programming Week 2 James King 12 August Creating Instances of Objects Basic Java Language Section.
Announcements The first graded lab will be posted Sunday 2/15 and due Friday 2/27 at midnight It is brand new, so please don’t hand in last semester’s.
22-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Programming section 3 2 Importing classes purpose packages CLASSPATH creating and using a package.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Objects Interaction and Source Code Week 2. OBJECT ORIENTATION BASICS REVIEW.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Libraries Programs that other people write that help you. #include // enables C++ #include // enables human-readable text #include // enables math functions.
Understanding class definitions Looking inside classes.
Object Oriented Software Development
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
1 Programming Section 11 James King 12 August 2003.
VARIABLES AND TYPES CITS1001. Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Scope.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Copyright Curt Hill Variables What are they? Why do we need them?
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
1 Programming 2 Aims Give overview of concepts addressed in Web based programming module Teach you enough Java to write simple web and network applications.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
LESSON 5 – Assignment Statements JAVA PROGRAMMING.
OOP Basics Classes & Methods (c) IDMS/SQL News
Java-02 Basic Concepts Review concepts and examine how java handles them.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Topic: Classes and Objects
Chapter 2 Basic Computation
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Lecture 5: Some more Java!
Object Oriented Programming
Multiple variables can be created in one declaration
Variables and Primative Types
Programming Language Concepts (CIS 635)
Chapter 2.
Class Structure 16-Nov-18.
Class Structure 28-Nov-18.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Expressions and Assignment
Class Structure 25-Feb-19.
Java Programming Language
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Problem 1 Given n, calculate 2n
Classes and Methods 15-Aug-19.
Presentation transcript:

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

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 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…

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 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…

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

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

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 created Attributes are created in the class definition, but outside any method Variables 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 a if a is used just before a = it can be modified if a is used anywhere else its contents are fetched

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 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 reserved You 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 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

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!

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

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.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) >=

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

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

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

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 true a==11 is false so we have true || false which is true so 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 true a==11 is false so we have true ^ false which is true so 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==10 b=!b; a==10 is true so b will have the value true but b=!b makes b become false; !

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

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

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

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; }

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

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 * ( ); The result is 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 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;

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

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

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 initialised Each 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(); 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