Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objects and Classes Lecture 12 Dr. Kevan Buckley CP1068 - Lecture 12.

Similar presentations


Presentation on theme: "Objects and Classes Lecture 12 Dr. Kevan Buckley CP1068 - Lecture 12."— Presentation transcript:

1 Objects and Classes Lecture 12 Dr. Kevan Buckley CP Lecture 12

2 Lecture Outcomes To fully understand primitive data types
Revision - we have been using these throughout To understand the fundamental concepts of object oriented programming. Objects Classes Methods Attributes To be able to write and test a small class CP Lecture 12

3 2 Types of Data Types Primitive Types Reference Types
Simple data items – e.g. one scalar value A variable of primitive type has a value Primitive types support operators The are 4 subgroups : integer, real, logical and character Reference Types Complex data A variable of reference type refers to (is bound to) an object References are essential for object-oriented programming We will look at these in the second part of this lecture An example you have already used (but is a special case) is String No operators (except for string concatenation) CP Lecture 12

4 Primitive Variables Every primitive variable stores a single primitive value of a specified type. Assignment may be used to transfers values between variables. Literals are used to include exact values in programs. int x = 10; int y = x; Using the equals operator like this is called assignment int is the data type used. int x is called a variable declaration. x and y are variables of type int – they can store whole numbers. 10 is an example of an integer literal. The first line copies the value10 into the variable x. The second line copies the contents of the x variable to the y variable. After these lines have been executed, both x and y will store 10. CP Lecture 12

5 These programs are equivalent – they all do the same.
Primitive Variables Each line of code here is called a statement Semicolons ;are used to separate statements. The example before included a variable declaration and an assignment in both lines of code. The variable declarations can be made separately. Variables must be declared before they are used. int x = 10; int y = x; int x; x = 10; int y; y = x; int x; int y; x = 10; y = x; int x, y; x = 10; y = x; These programs are equivalent – they all do the same. CP Lecture 12

6 Assignment Statements
The general form of assignment is An expression can be: a variable a literal a combination of variables and literals and operators. variableName = expression; int x = 10; int y, z; y = x + 2; z = 2 * y + x; * multiplication / division What is stored in z at the end? CP Lecture 12

7 Integer Types Integer means whole number
e.g. how many holes did the navvy dig – 4 e.g. how many exams did you pass - 8 The are no decimal points/places Choose the exact data type to use depending on the size of your numbers. If you needed to store a whole number between 1 and 1000, which type would you use? CP Lecture 12

8 Real Data Types A real number is one that can contain fractional parts. i.e. a decimal point/decimal places. e.g. batteryVoltage = 1.5 There are a choice of real types in Java Use different amount of memory Operate with different levels of precision. i.e. how many decimal places they can accurately store. double pi = 3.14; double radius = 1.1; double area = pi * radius * radius; CP Lecture 12

9 Logical Data The boolean data type is used to store logical data
Boolean variables can have only one of two possible values true false Logical operators work on booleans Relational operators work on numbers to result in booleans boolean a = true; boolean b = false; boolean c; c = b; && || < > >= <= == != CP Lecture 12

10 Textual Data The char data type uses one byte of memory to store one text character. e.g. one letter or digit. Single quotes must surround character literals. If you need to store more than one character you must use the String type. char firstLetter = 'A'; char anotherChar = '9'; char yetAnotherChar = firstLetter; CP Lecture 12

11 Strings String is a data type for storing textual data.
String is not a primitive type, but is a special case, that behaves like one in some cases. It is actually a reference type More on this later in module String variables can be used like the primitives Literals must be enclosed in double quotes String someWords = "Hello Java Fan"; String moreWords; moreWords = someWords; CP Lecture 12

12 Constants Constants are like variables, but their value cannot change.
Helps maintenance Give a descriptive name to a value A single change can affect the whole program No confusing "magic numbers" Achieved by putting the final keyword in the variable declaration/assignment. If you try to change a constant you will get a compiler error. final double VAT_RATE = 0.175; double originalCost = 22.95; double costWithVAT = originalCost * VAT_RATE; CP Lecture 12

13 Object Oriented Programming
Complex Data Types CP Lecture 12

14 Object-Orientation Object-oriented design (OOD)
Models real-world objects Models communication among objects Encapsulates data (attributes) and functions (behaviors) Information hiding Communication through well-defined interfaces Object-oriented language Used to implement OO designs Programming is called object-oriented programming (OOP) Java CP Lecture 12

15 Objects in the Real World
Definition (Riley 2003) An object is an entity that has: State – what the object looks like Behaviour – how the object acts Examples A pizza A loud speaker States - Brown & red with other coloured bits Behaviour – Not a lot. Cools down? States – Round and black Behaviour – Converts electric signals to sound? Complex objects A radio Incorporates other objects such as a loud speaker. More complex behaviour. CP Lecture 12

16 State and Behaviour Attributes define the state of an object
Called instance variables in Java Attributes have a name, type and value e.g. a car might have an attribute with the name bodyColour of type colour and has the value red Methods define the behaviour of an object Similar to functions or procedures in other programming languages Methods have names that should indicate their behaviour e.g. a car might have a method moveForward CP Lecture 12

17 Objects in Software Graphical User Interface Supermarket Layout System
A window on the screen Caption bar Close button, minimise button, maximise button Scrollbar Up button, down button, slider Main part Graphics and text Objects are composed of other objects Supermarket Layout System Aisle Shelf Product – tin, jar, bottle, bag Refrigerator Checkout CP Lecture 12

18 Classes Definition Examples
Every object belongs to a group of objects of the same type called the object’s class. A class defines the types of states and behaviour belonging to a group of objects Examples My Ferrari – Belongs to the car class Wolverhampton Wanderers – Football club class MI035 – Computing laboratory CP Lecture 12

19 Object vs. Classes Class Object
A template that defines attributes and methods Written by programmer as part of program Cannot be altered during program execution Is named by a class name Object Must belong to some class Exists whilst the program is executing Must be declared and constructed by a program Has attributes with values and methods that can execute Class defines these Referenced by an identifier (variable name) CP Lecture 12

20 UML Class Diagrams The Unified Modelling Language (UML) provides a variety of diagrams for describing software. Class diagrams are used to specify a class 3 sections: Class name Instance variables Methods TV isOn : boolean channel : int void press1() void press2() void press3() void pressStandby() Remember that: "Instance Variable" is another name for attribute or property. "Methods" provide the object's behaviour. CP Lecture 12

21 Instance Variables The class diagram specifies the type of instance variables. The TV class has 2 instance variables that define its state: isOn – stores whether the TV is in standby or is on boolean channel – stores the current channel number int primitive data types Name Description Example int Integer. Whole number 78 double Floating point number. Decimal places 73.65 boolean Boolean true/false value true String Textual data Hello Classes may have any number of member (instance) variables of any types. For example: class Anyclass{ int x; float y; char a,b; } There are scoping rules which apply to variables declared in classes. If they are declared outside a method then they are in scope in all the methods of the class. If they are declared inside a method the are only in scope within that method. Java will generate a syntax error if a variable is not initialised before it is used. Java automatically initialises all the instance variables of an object when it is created. All numeric values (including chars) are set to zero. Everything not numeric is an object reference and is set to null (see later in this lecture). These may not be sensible values for the instance variables. Instance variables may have a sensible default value specified in their declaration. In the case of Heater the single instance variable on has a default value of true. Constructors (see later) may also be used to give default values to instance variables. CP Lecture 12

22 This is a very imporant slide
Instance Variables Scope: Instance variables may be accessed by all the methods in the class Variables declared in methods are local to the method and cannot be seen outside it. All variables in Java must be initialised before use When an object is instantiated the default values of its variables are 0 or null This is not the case with local variables, as we shall see. Sensible default values for can be set in the class definition or by a Constructor (covered later). Classes may have any number of member (instance) variables of any types. For example: class Anyclass{ int x; float y; char a,b; } There are scoping rules which apply to variables declared in classes. If they are declared outside a method then they are in scope in all the methods of the class. If they are declared inside a method the are only in scope within that method. Java will generate a syntax error if a variable is not initialised before it is used. Java automatically initialises all the instance variables of an object when it is created. All numeric values (including chars) are set to zero. Everything not numeric is an object reference and is set to null (see later in this lecture). These may not be sensible values for the instance variables. Instance variables may have a sensible default value specified in their declaration. In the case of Heater the single instance variable on has a default value of true. Constructors (see later) may also be used to give default values to instance variables. This is a very imporant slide CP Lecture 12

23 Methods Methods have The TV class has 4 methods a name a return type
The type of data to be passed from a method Specified before the method name Keyword void indicates no data is returned parameters Data to be passed to the method Type of data is listed between ( ) after the method name The TV class has 4 methods All require no parameters and return no values. inputs and outputs of methods CP Lecture 12

24 Creating Objects An object is an instance of a class
An object is constructed or instantiated from a class Instantiation is done with the new operator An object reference is used to refer to an object Declaration of an TV object reference called myTV TV myTV; myTV = new TV(); Construction and assignment of a TV object new Operator TV constructor CP Lecture 12

25 Accessing Methods and Attributes
An object reference acts as an alias for an object Object references can be used to access instance variables and methods Object-reference.variable-name Object-reference.method-name Examples: myTV.channel = 1; Sets the channel instance variable of the myTV object to the value 1 myTV.press2(); Calls the press2 method of the myTV object Once created an object reference is a means of accessing and manipulating the object. It behaves a little bit like a pointer in C++, however it doesn't have to be dereferenced and it can't be manipulated arithmetically. Object references are used to access the methods and variables of the object they represent. CP Lecture 12

26 Object-reference.method-name
Examples of Methods The String class has useful methods What does this code do? String txt = "Hello World"; System.out.println(txt.length()); System.out.println(txt.charAt(6)); System.out.println(txt.indexOf('e')); System.out.println(txt.startsWith("Hell")); Object-reference.method-name Did we use any methods or attributes last week when we looked at files? String is a special class where objects can be constructed implicitly (as shown here). Other classes need to use a Constructor. CP Lecture 12

27 Constructors Constructors Default Constructor
Similar to methods and invoked when an object is created Used to perform additional initialisation Constructor has same name as class No return type Can be overloaded Default Constructor Constructor without parameters Invoked if no other constructor is specified when object is created Automatically created by Java if not explicitly declared class TV { boolean isOn; int channel; TV() { channel = 1; isOn = false; } Another way in which the instance variables of an object may be initialised is via a constructor. In fact a constructor may do much more than just set the values of instance variables. A constructor is a method but a special type of method. As we shall see later a constructor is always invoked when an object is created. Constructor methods always have the same name as the class they belong to. They do not have a return type (not even void). Constructor methods may be overloaded in the same way as ordinary methods. One special type of constructor is known as the default constructor. This is a constructor without any parameters. Every class must have a default constructor and Java will create one if the programmer does not define one. The default constructor created by Java will set all numeric instance variables to 0 and all object references to null. CP Lecture 12

28 TV Class TV isOn : boolean channel : int TV() press1() : void
boolean isOn; int channel; TV() { channel = 1; isOn = false; } void press1() { void press2() { channel = 2; void press3() { channel = 3; void pressStandby() { isOn = !isOn; instance variables TV isOn : boolean channel : int TV() press1() : void press2() : void press3() : void pressStandby() : void constructor methods CP Lecture 12

29 Demo Using BlueJ Repeat what the tutor has just shown you
Create and test the TV class class TV { boolean isOn; int channel; TV() { channel = 1; isOn = false; } void press1() { void press2() { channel = 2; } void press3() { channel = 3; void pressStandby() { isOn = !isOn; CP Lecture 12

30 Quiz 1. Identify an instance variable 2. Identify a compiled class
3. Identify an object 4. Identify a method Which of the following is not correct? An object is an instance of a class, created by a constructor. A class defines the structure of a group of related objects. An object is used by an instance variable to create a class. Instance variables store the state of an object, whilst methods provide the method's behaviour. CP Lecture 12

31 Kinds of Variables Instance variables Parameter variable Local
class Person { int age; String name; void setName(String nm) { name = nm; } int getTwiceAge() { int twice; twice = age * 2; return twice; Instance variables Parameter variable Local variable CP Lecture 12

32 Types of Variables & Scope
Instance variables Defined inside a class, but outside all methods Used to store the state of an object Can be accessed from any method in the class Automatically initialised - given default values Parameter variables Defined in a method header Used to pass data to a method Can only be accessed from the method they are defined in Initialised by values from the caller Local variables Defined inside a method Used for storing intermediate/temporary values Must be explicitly initialised before they can be used Print this slide and put it somewhere that you will notice it regularly CP Lecture 12

33 Update Methods Update methods are used to pass new values for instance variables to an object. Changes the state of the object. Data is passed to the method via a parameter variable. An assignment statement is used to copy the value from the parameter variable to the instance variable. The method has void return type because it does not return anything. class Person { int age; String name; void setName(String nm) { name = nm; } void setAge(int a) { age = a; Person p = new Person(); p.setName("jane"); p.setAge(22); CP Lecture 12

34 Query Methods Query methods are used to interrogate an object to find out the value of an instance variable. Data is passed from the method using the return statement. An assignment statement is used in the calling program to make a copy of the instance variable. class Person { int age; String name; String getName() { return name; } int getAge() { return age; String n = p.getName(); int a = p.getAge(); CP Lecture 12

35 Summary Update and query methods are provided for all instance variables that the user may have access to. One update method and one query method is usual per instance variable. Update methods pass new values for instance variables to an object. Always have the return type void Always have one parameter Query methods determined the current instance variable values of an object. Do not have any parameters Return data of the type of the instance variable. CP Lecture 12

36 Ambiguity Between Variables
class Person { String name; void setName(String name) { name = name; } Person p = new Person(); p.setName("frank"); Q. What is the result of executing this code? A. A Person object is constructed and its name instance variable is set to null. Why. setName does not effect the instance variable. The code refers only to the parameter variable. CP Lecture 12

37 Resolving Ambiguity The this reference points to the current object.
this.name therefore references the instance variable called name belonging to the current object. class Person { String name; void setName(String name) { this.name = name; } This line copies the value from the parameter variable to the instance variable. CP Lecture 12

38 Exercise Implement and test the person class
Implement and test a ComputingLab class Make sure you use appropriate data types for attributes void setName(String name) { this.name = name; } void setAge(int age) { this.age = a; String getName() { return name; } int getAge() { return age; class Person { int age; String name; Person() { this.age = 0; this.name = "unknown"; } CP Lecture 12

39 Default Constructors Constructors are like methods:
But have no return type (not even void) Must have exactly the same name as the class Can be overloaded Default constructor has no parameters Used to give initial values to instance variables If you do not supply a default constructor, the compiler will generate one for you. But its behaviour might not be what you want CP Lecture 12

40 Parameterised Constructors
Parameterise constructors require the caller to supply parameters Parameters are used to initialise instance variables Saves the caller calling update methods just after the default constructor This is what you have to do in some semi-OO languages such as VB 6. Constructor uses similar syntax to update methods The this reference is used to resolve ambiguity Can have various different overloaded versions of constructors for complex classes Allow the user to specify some parameters, but use defaults for others. CP Lecture 12

41 House Class Instance variables Default constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 class House { int number; String street; House() { number = 0; street = "not known"; } House(int number, String street) { this.number = number; this.street = street; Instance variables Default constructor Parameterised constructor What query and update methods should this class have? CP Lecture 12

42 House Class 1 2 3 4 5 6 7 8 9 10 11 12 class House { int number;
String street; House() { number = 0; street = "not known"; } House(int number, String street) { this.number = number; this.street = street; 13 14 15 16 17 18 int getNumber() { return number; } void setNumber(int number){ this.number = number; 19 20 21 22 23 24 25 String getStreet() { return street; } void setStreet(String street){ this.street = street; CP Lecture 12

43 Naming Conventions Variable and method names normally start with a lower case letter Words within the name are capitalised heightOfBox Class names begin with a capital letter HelloWorldApplet See the Java coding conventions To make programs more readable many Java programmers adopt a simple convention in naming the elements of a program. The first letter in the name of a variable or a method is normally lower case. The first letter of a class name is normally upper case. Typically Java programmers name things with a string of words e.g. theAreaOfTheCircle. The first character of such a name follows the rules above, if it is the name of a class then it is upper case otherwise lower case. After that the first letter of each word in is uppercase. CP Lecture 12

44 Coding Conventions Why Have Code Conventions?
80% of the lifetime cost of a piece of software goes to maintenance. Hardly any software is maintained for its whole life by the original author. Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create. For the conventions to work, every person writing software must conform to the code conventions. Everyone! Why Have Code Conventions? Code conventions are important to programmers for a number of reasons: • 80% of the lifetime cost of a piece of software goes to maintenance. • Hardly any software is maintained for its whole life by the original author. • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create. For the conventions to work, every person writing software must conform to the code conventions. Everyone. This was taken from java.sun.com coding conventions page. CP Lecture 12

45 Additional Material CP Lecture 12

46 UML Object Diagrams Used to show the state of objects at runtime
There are 2 alternatives for including the reference id channel = 2 isOn = true myTV : TV myTV We will use these extensively next week CP Lecture 12

47 Dry Running Technique for analysing the behaviour of a program
To see what it does To see how it works To identify bugs Each program instruction is taken in turn and its effect is written down Keeps a record of the instructions that were executed and the order in which they were executed. Keeps a record of the way data is manipulated in the program. CP Lecture 12

48 Example Program 1 1 2 3 4 1 2 3 4 TV tv; tv = new TV();
tv.channel = 3; tv.isOn = true; 1 tv null :TV channel = 1 isOn = false 2 tv :TV channel = 3 isOn = false 3 tv :TV channel = 3 isOn = true 4 tv CP Lecture 12

49 Which channels are being watched at the end of the code?
Example Program 2 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv; kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; Which channels are being watched at the end of the code? 1 kevsTv null davesTv helensTv CP Lecture 12

50 Program 2 2 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv;
kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; 2 kevsTv davesTv null helensTv :TV channel = 1 isOn = false CP Lecture 12

51 Program 2 3 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv;
kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; 3 kevsTv davesTv helensTv null :TV channel = 1 isOn = false CP Lecture 12

52 Program 2 4 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv;
kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; 4 kevsTv davesTv helensTv null :TV channel = 2 isOn = false channel = 1 CP Lecture 12

53 Program 2 5 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv;
kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; 5 kevsTv davesTv helensTv null :TV channel = 2 isOn = false channel = 3 CP Lecture 12

54 Program 2 6 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv;
kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; 6 kevsTv davesTv helensTv :TV channel = 2 isOn = false channel = 3 CP Lecture 12

55 Program 2 7 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv;
kevsTv = new TV(); davesTv = new TV(); kevsTv.channel = 2; davesTv.channel = 3; helensTv = kevsTv; 7 kevsTv davesTv helensTv :TV channel = 2 isOn = false channel = 3 channel = 1 CP Lecture 12

56 Null Pointer Exceptions
When a reference is null it cannot be used to access an object. It is not actually referencing an object. Causes a NullPointerException. Program terminates The most common type of runtime error 1 tv null 1 2 TV tv; tv.channel = 3; 2 null pointer exception tv is not actually referencing an object when the assignment is attempted CP Lecture 12

57 Orphans When an object is no longer referenced by a program it becomes an orphan It is no longer accessible The memory it is using will be recycled by the JVM This will not cause the memory leak that would occur in other languages. When you dry run a program orphans are objects that do not have any arrows pointing to them. CP Lecture 12

58 Orphans 1 2 4 3 Orphan 1 2 3 4 TV tv1, tv2; tv1 = new TV();
null tv2 2 tv1 tv2 null :TV channel = 1 isOn = false 4 :TV channel = 1 isOn = false tv2 tv1 3 :TV channel = 1 isOn = false tv2 tv1 Orphan In Java, orphaned objects are deleted. CP Lecture 12

59 Example Program 3 1 2 3 4 5 6 7 TV kevsTv, davesTv, helensTv; kevsTv = new TV(); kevsTv.press2(); davesTv = new TV(); helensTv = kevsTv; davesTv.press3(); helensTv.press1(); After this code is run, which channel is kevsTV tuned into. CP Lecture 12

60 Answer TV kevsTv, davesTv, helensTv; kevsTv = new TV();
kevsTv.press2(); davesTv = new TV(); helensTv = kevsTv; davesTv.press3(); helensTv.press1(); CP Lecture 12

61 Scope of Variables Scope refers to where variables are known.
The scope of an instance variable is the class in which it is declared The scope of a local variable is the innermost { … }. What are the problems in this program? 1 2 3 4 5 6 7 8 9 10 11 12 13 class Thingy { int x; void f1(int x) { int y; y = x * x; x = y; } void f2() { x = y * y; The assignment in line 7 does not affect the x instance variable. (this might not be the intention anyway) Accessing y on line 11 is a syntax error. y is out of scope in f2. y is declared in method f1 so only exists within f1, not f2. Local variables are preferable programming style to instance variables. CP Lecture 12

62 Variable Initialisation
1 2 3 4 5 6 7 8 9 10 11 12 class Thingy { int x, y; void f1() { x = y * y; } void f2() { int z; x = z + 2; What are the problems in this program? Instance variables are automatically initialised. x and y therefore have initial values of 0. Line 5 would not cause a problem, but would set x to 0 multiplied by 0. Local variables need to be initialised before they are used. Line 10 would be detected as an error at compile time. The program tries to use a value of z that has not been initialised. CP Lecture 12

63 Overloaded Methods It is possible to have more than one method with the same name. Called overloading methods Must have different parameter types Must have the same return type double calculateCost(double price) { double taxRate = 1.175; return price * taxRate; } Method uses default tax rate double calculateCost(double price, double taxRate) { return price * taxRate; } User specifies tax rate CP Lecture 12


Download ppt "Objects and Classes Lecture 12 Dr. Kevan Buckley CP1068 - Lecture 12."

Similar presentations


Ads by Google