Object Oriented Programming Dr Robert Harle

Size: px
Start display at page:

Download "Object Oriented Programming Dr Robert Harle"

Transcription

1 Object Oriented Programming Dr Robert Harle IA NST CS and CST Lent 2009/10 Handout 1 OO Programming This is a new course this year that absorbs what was Programming Methods and provides a more formal look at Object Oriented programming with an emphasis on Java Four Parts Computer Fundamentals Object-Oriented Concepts The Java Platform Design Patterns and OOP design examples If we teach Java in isolation, there s a good chance that students don t manage to mentally separate the object-oriented concepts from

2 Java s implementation of them. Understanding the underlying principles of OOP allows you to transition quickly to a new OOP language. Because Java is the chosen teaching language here, the vast majority of what I do will be in Java, but with the occasional other language thrown in to make a point. Actually learning to program is best done practically. That s why you have your practicals. I don t want to concentrate on the minutiae of programming, but rather the larger principles. It might be that some of this stuff will make more sense when you ve done your practicals; I hope that this material will help set you up to complete your practicals quickly and efficiently. But we ll see. Java Ticks This course is meant to complement your practicals in Java Some material appears only here Some material appears only in the practicals Some material appears in both: deliberately! A total of 7 workbooks to work through Everyone should attend every week CST: Collect 7 ticks NST: Collect at least 5 ticks

3 Books and Resources OOP Concepts Look for books for those learning to first program in an OOP language (Java, C++, Python) Java: How to Program by Deitel & Deitel (also C++) Thinking in Java by Eckels Java in a Nutshell (O' Reilly) if you already know another OOP language Lots of good resources on the web Design Patterns Design Patterns by Gamma et al. Lots of good resources on the web Books and Resources Also check the course web page Updated notes (with annotations where possible) Code from the lectures Sample tripos questions There really is no shortage of books and websites describing the basics of object oriented programming. The concepts themselves

4 are quite abstract, but most texts will use a specific language to demonstrate them. The books I ve given favour Java (because that s the primary language you learn this term). You shouldn t see that as a dis-recommendation for other books. In terms of websites, SUN produce a series of tutorials for Java, which cover OOP: but you ll find lots of other good resources if you search. And don t forget your practical workbooks, which will aim not to assume anything from these lectures.

5 Chapter 1 Computer Fundamentals What can Computers Do? The computability problem Given infinite computing 'power' what can we do? How do we do it? What can't we do? Option 1: Forget any notion of a physical machine and do it all in maths Leads to an abstract mathematical programming approach that uses functions Gets us Functional Programming (e.g. ML) λ Option 2: Build a computer and extrapolate what it can do from how it works Not so abstract. Now the programming language links closely to the hardware This leads naturally to imperative programming (and on to object-oriented) 5

6 What can Computers Do? The computability problem Both very different (and valid) approaches to understanding computer and computers Turns out that they are equivalent Useful for the functional programmers since if it didn't, you couldn't put functional programs on real machines... WWII spurred an interest in machinery that could compute. During the war, this interest was stoked by a need to break codes, but also to compute relatively mundane quantities such as the trajectory of an artillery shell. After the war, interest continued in the abstract notion of computability. Brilliant minds (Alan Turing, etc) began to wonder what was and wasn t computable. They defined this in an abstract way: given an infinite computing power (whatever that is), could they solve anything? Are there things that can t be solved by machines? Roughly two approaches to answering these questions appeared: Maths, maths, maths. Ignore the mechanics of any real machine and imagine a hypothetical machine that had infinite computation power, then write some sort of programming language for it. This language turned out to be a form of mathematics known as Lambda calculus. It was based around the notion of functions in a mathematical sense.

7 Build it and they will come. Understand how to build and use a real computing machine. This resulted in the von Neumann architecture and the notion of a Turing machine (basically what we would call a computer). It turned out that both approaches were useful for answering the fundamental questions. In fact, they can be proven to be the same thing now! Imperative This term you transition from functional (ML) to imperative (Java) Most people find imperative more natural, but each has its own strengths and weaknesses Because imperative is a bit closer to the hardware, it does help to have a good understanding of the basics of computers. All the CST Students have this All the NST students don't... yet. All this is very nice, but why do you care? Well, there s a legacy from these approaches, in the form of two programming paradigms: Functional Languages. These are very mathematically oriented and have the notion of functions as the building blocks of computation.

8 Imperative or Procedural Languages. These have variables (state) and procedures as the main building blocks 1. Such languages are well known e.g. C and include what we call objectoriented languages such as C++ and Java. Note that I have pluralised Language in the above sentences. Terms like Object-oriented are really a set of ideas and concepts that various languages implement to varying degrees. Last term you toured around Computer Science (in FoCS) and used a particular language to do it (ML). Although predominantly a functional programming language, ML has acquired a few imperative features so you shouldn t consider it as a pure functional language. (For example, the ML reference types you looked at are not functional!). This term you will shift attention to an object-oriented language in the form of Java. What we will be doing in this course is looking at the paradigm of object-oriented programming itself so you can better understand the underlying ideas and separate the Java from the paradigm. 1.1 Hardware Fundamentals As I said before, the imperative style of programming maps quite easily to the underlying computer hardware. A good understanding of how computers work can greatly improve your programming capabilities with an imperative language. Thing is, only around a half of you have been taught the fundamentals of a computer (the 1 A procedure is a function-like chunk of code that takes inputs and gives outputs. However, unlike a formal function it can have side effects i.e. can make non-local changes to something other than its inputs and declared outputs.

9 CST half). Those people will undoubtedly be rather bored by what follows in the next few pages, but it s necessary so that everyone is at the same point when we start to delve deeper into object-oriented programming. Computers do lots of very simple things very fast. Over the years we have found optimisation after optimisation to make the simple processes that little bit quicker, but really the fundamentals involve some memory to store information and a CPU to perform simple actions on small chunks of it. We use lots of different types of memory, but conceptually only two are of interest here. System memory is a very large pool of memory (the 2GB or so you get when you buy a machine). Then there are some really fast, but small chunks of memory called registers. These are built into the CPU itself. The CPU acts only on the chunks in the registers so the computer is constantly loading chunks of data from system memory into registers and operating on the register values. The example that follws loads in two numbers and adds them. Those doing the Operating Systems course will realise this is just the fetchexecute cycle. Basically, there is a special register called the program counter (marked P) that tells the computer where to look to get its next instruction. Here I ve made up some operations: LAM. LOAD the value in memory slot A into register M AMNO. ADD the values in registers M and N and put the result in register O. SMA. STORE the value in register M into memory slot A

10 Dumb Model of a Computer Memory L6X L7Y AXYZ SZ Registers CPU P 1 X Y Z ALU Dumb Model of a Computer Memory L6X L7Y AXYZ SZ Registers CPU P X 2 63 Y Z ALU

11 Dumb Model of a Computer Memory L6X L7Y AXYZ SZ Registers CPU P X Y Z ALU Dumb Model of a Computer Memory L6X L7Y AXYZ SZ Registers CPU P X Y Z ALU All a computer does is execute instruction after instruction. Never forget this when programming!

12 Memory (RAM) Memory You probably noticed we view memory as a series of slots Each slot has a set size (1 byte or 8 bits) Each slot has a unique address Each address is a set length of n bits Mostly n=32 or n=64 in today s world Because of this there is obviously a maximum number of addresses available for any given system, which means a maximum amount of installable memory We slice system memory up into 8-bit (1 byte) chunks and give each one an address (i.e. a slot number). Each of the registers is a small, fixed size. On today s machines, they are usually just 32 or 64 bits. Since we have to be able to squeeze a memory address into a single register, the size of the registers dictates how much of the system memory we can use. Q1. How much system memory can we use if we have 8, 32 or 64 bit registers?

13 Big Numbers So what happens if we can t fit the data into 8 bits e.g. the number 512? We end up distributing the data across (consecutive) slots Memory Now, if we want to act on the number as a whole, we have to process each slot individually and then combine the result Perfectly possible, but who wants to do that every time you need an operation? If I have two lots of 128-bits of data, how do I add them together on a 32 bit machine? I can t squeeze 128 bits into 32 bits. I have to chop the 128 bits up into 32 bit chunks, add corresponding chunks together and then put those new chunks back together again to get a 128-bit answer. Can you imagine having to do this every time you needed to do an addition? Nasty.

14 High Level Languages Instead we write in high-level languages that are human readable (well, compsci-readable anyway) High-Level Source Code (e.g. C++, Java) Compiler Binary executable (i.e. CPU-speak) You already know the solution from FoCS and ML. We build up layers of abstractions and write tools to drill down from one layer to the next. We program in high level code and leave it to the compiler to figure out that when we say c=a+b; we actually mean chop up a and b, load them into registers, add them, look out for overflow, then put all the pieces back together in memory somewhere called c.

15 1.2 Functional and Imperative Revisited We said imperative programming developed from consideration of the hardware. Given the hardware we ve just designed, the logical thing to do is to represent data using state. i.e. explicit chunks of memory used to store data values. A program can then be viewed as running a series of commands that alter ( mutate ) that state (hopefully in a known way) to give the final result. So c=a+b is referring to three different chunks of memory that represent numbers. Unlike in ML, it is perfectly valid to say a=a+b, which computes the sum and then overwrites the state stored in a. Functional programs, on the other hand, can be viewed as independent of the machine. Strictly speaking, this means they can t have state in the same way since there s simply nowhere to put it (no notion of memory). Instead of starting with some data that gets mutated to give a result, we only have an input and an output for each function. Of course, ML runs on real machines and therefore makes use of real hardware components such as memory. But that s because someone has mapped the ideal mathematical processes in functional code to machine operations (this must be possible because I said both the mathematical view and the system view are equivalent). The key point is that, although functional code runs on real hardware, it is independent of it since it is really a mathematical construct. Most people find the imperative approach easier to understand and, in part, that is why it has gained such a stronghold within modern programming languages.

16 1.3 Machine Architectures Machine Architectures Actually, there s no reason for e.g ARM and Intel to use the same instructions for anything and they don t! The result? Any set of instructions for one processor only works on another processor if they happen to use the same instruction set... i.e. The binary executable produced by the compiler is CPUspecific We say that each set of processors that support a given set of instructions is a different architecture E.g. x86, MIPS, SPARC, etc. But what if you want to run on different architectures?? Compilation So what do we have? We need to write code specifically for each family of processors... Aarrggh! The solution : C++ Compiler for x86 Source Code (e.g. C+ +) C++ Compiler for ARM Binary executable for PC (x86) Binary executable for ARM

17 Remember those weird commands I made up when we did the fetchexecute cycle? Well, not all CPUs are equivalent: newer ones have cool new instructions to do things better. All that means is that a set of instructions for CPU X won t mean anything to CPU Y unless the manufacturers have agreed they will. Q2. Why do you think CPU manufacturers haven t all agreed on a single set of instructions? There is one very popular set of machine instructions known as x86. Basically, these were what IBM came up with for the original PC. Now the term PC has come to mean a machine that supports at least the set of x86 instructions. Manufacturers like Apple traditionally chose not to do so, meaning that Mac applications couldn t run on PC hardware and vice-versa. Q3. Apple recently started using Intel processors that support x86 instructions. This means Apple machines can now run Microsoft Windows. However, off-the-shelf PC software (which is compiled for x86) does not run on a Mac that is using the Apple operating system compiled for the Intel processor. Why not?

18 Enter Java Sun Microcomputers came up with a different solution They conceived of a Virtual Machine a sort of idealised computer. You compile Java source code into a set of instructions for this Virtual Machine ( bytecode ) Your real computer runs a program (the Virtual machine or VM) that can efficiently translate from bytecode to local machine code. Java is also a Platform So, for example, creating a window is the same on any platform The VM makes sure that a Java window looks the same on a Windows machine as a Linux machine. Sun sells this as Write Once, Run Anywhere Java compiles high-level source code not into CPU-specific instructions but into a generic CPU instruction set called bytecode. Initially there was no machine capable of directly using bytecode, but recently they have started to appear in niche areas. Therefore you usually run bytecode programs inside the virtual machine (which has been compiled specifically for your architecture). This converts bytecode instructions into meaningful instructions for your local CPU. All the CPU-specific code goes into the virtual machine, which you should just think of as a piece of intermediary software that translates commands so the local hardware can understand. SUN publishes the specification of a Java Virtual Machine (JVM) and anyone can write one, so there are a plenty available if you want to explore. Start here:

19 1.4 Types Types and Variables We write code like: int x = 512; int y = 200; int z = x+y; The high-level language has a series of primitive (built-in) types that we use to signify what s in the memory The compiler then knows what to do with them E.g. An int is a primitive type in C, C++, Java and many languages. It s usually a 32-bit signed integer A variable is a name used in the code to refer to a specific instance of a type x,y,z are variables above They are all of type int Primitive Types in Java Primitive types are the built in ones. They are building blocks for more complicated types that we will be looking at soon. boolean 1 bit (true, false) char 16 bits byte 8 bits as a signed integer (-128 to 127) short 16 as a signed integer int 32 bits as a signed integer long 64 bits as a signed integer float 32 bits as a floating point number double 64 bits as a floating point number [See practicals]

20 You met the notion of types in FoCS and within ML. They re important because they allow the compiler to keep track of what the data in its memory actually means and stop us from doing dumb things like interpreting a floating point number as an integer. In ML, you know you can specify the types of variables. But you almost never do: you usually let the compiler infer the type unless there s some ambiguity (e.g. between int and double). In an imperative language such as Java you must explicitly assign the types to the variable. For any C/C++ programmers out there: yes, Java looks a lot like the C syntax. But watch out for the obvious gotcha a char in C is a byte (an ASCII character), whilst in Java it is two bytes (a Unicode character). If you have an 8-bit number in Java you may want to use a byte, but you also need to be aware that a byte is signed..! You do lots more work with number representation and primitives in your Java practical course. You do a lot more on floats and doubles in your Floating Point course.

21 Reference Types (Classes) Lets imagine you re creating a program that stores info about someone doing CS You might create a set of variables (instances of types) as follows: String forename = Kay ; String surname = Oss ; Now you need to represent two people so you add: String forename2 = Don ; String surname2 = Keigh ; Now you need to add more this is getting rather messy Better if we could create our own type call it a Person Let it contain two values: forename and surname Reference Types (Classes) public class Person { String forename; String surname; In Java we create a class which acts as a blueprint for a custom type A class: Has attributes (things it is assigned e.g. name, age) Has methods (things it can do e.g. walk, think) When we create an instance of a class we: Assign memory to hold the attributes Assign the attributes We call the instance an object As in object-oriented programming You ve met things called reference types in ML so hopefully the idea of a reference isn t completely new to you. But if you re wondering

22 why classes are called reference types in Java, we ll come to that soon. Definitions Class A class is a grouping of conceptually-related attributes and methods Object An object is a specific instance of a class Once we have compiled our Java source code, we end up with a set of.class files. We can then distribute these files without their source code (.java) counterparts. In addition to javac you will also find a javap program which allows you to poke inside a class file. For example, you can disassemble a class file to see the raw bytecode using javap -c classfile: Input: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World");

23 javap output: Compiled from "HelloWorld.java" public class HelloWorld extends java.lang.object{ public HelloWorld(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/object."<init>":()v 4: return public static void main(java.lang.string[]); Code: 0: getstatic #2; //Field java/lang/system.out: //Ljava/io/PrintStream; 3: ldc #3; //String Hello World 5: invokevirtual #4; //Method java/io/printstream.println: //(Ljava/lang/String;)V 8: return This probably won t make a lot of sense to you right now: that s OK. Just be aware that we can view the bytecode and that sometimes this can be a useful way to figure out exactly what the JVM will do with a bit of code. You aren t expected to know bytecode.

24 1.5 Pointers and References Pointers In some languages we have variables that hold memory addresses. These are called pointers MyType x; MyType *xptr1 = &x; MyType *xptr2 = xptr1; C++ xptr1 x xptr2 A pointer is just the memory address of the first memory slot used by the object The pointer type tells the compiler how many slots the whole object uses A pointer is just the name given to memory addresses when we handle them in code. They are very powerful concepts to work with, but you need to take a lot of care. Java doesn t expose pointers to the programmer, so we ll use some basic C examples to make some points in the lectures. There are just a few bits of C you may need to know to follow: int x declares a variable x that is a 32-bit signed integer int *p declares a pointer p that can point to an int in memory. It must be manually initialised to point somewhere useful. p=&x Gets the memory address for the start of variable x and stick it in p so p is a pointer to x. int a=*p declares a new int variable called a and sets its value to that pointed to by pointer p. We say that we are dereferencing

25 p. If it helps, we can map these operations to ML something like 2 : C ML Comments int x let val xm=0 in... xm is immutable int *p let val pm=ref 0 in... pm is a reference to a variable initially set to zero p=&x val pm = ref xm int a=*p val am =!pm The key point to take away is that a pointer is just a number that maps to a particular byte in memory. You can set that number to anything you like, which means there s no guarantee that it points to anything sensible..! And the computer just obeys if you say that a pointer points to an int, then it doesn t argue. Working with pointers helps us to avoid needless copies of data and usually speeds up our algorithms (see next term s Algorithms I course). But a significant proportion of program crashes are caused by trying to read or write memory that hasn t been allocated or initialised... 2 Now, if all that reference type stuff in ML confused you last term, don t worry about making these mappings just now. Just be aware that what will come naturally in imperative programming has been retrofitted to ML, where it seems a little less obvious! For now, just concentrate on understanding pointers and references from scratch.

26 Java s Solution? You can t get at the memory directly. So no pointers, no jumping around in memory, no problem. Great for teaching. It does, however, have references These are like pointers except they are guaranteed to point to either an object in memory or null. So if the reference isn t null, it is valid In fact, all objects are accessed through references in Java Variables are either primitive types or references! Remember that classes are called Reference Types in Java. This is because they are only handled by reference. Code like: MyClass m = new MyClass(); creates an instance of MyClass somewhere in main memory (that s what goes on on the right of the equals). And then it creates a reference to that instance and stores the result in a variable m. A reference is really just a special kind of pointer. Remember that a pointer is just a number (representing a memory slot). We can set a pointer to any number we like and so it is possible that dereferencing it gets us garbage. A reference, however, always has a valid address or possibly a special value to signify it is invalid. If you dereference a reference without the special value in it, the memory you read will contain something sensible.

27 In Java, the special value is signified using the keyword null: MyClass m = null;... m = new MyClass(); // Not initialised If you try to do something with a reference set to null, Java will bail out on you. To test whether a reference is null: 3 if (m==null) {... Q4. Pointers are problematic because they might not point to anything useful. A null reference doesn t point to anything useful. So what is the advantage of using references over pointers? 3 Note that the Java/C syntax uses = for assignment and == for comparison. We ll discuss this in more detail later.

28 References int p1 = 50; int p2 = p1; Person r1 = new Person(); r1.name= Bob ; Person r2 = p; P1 (50) P2 (50) r1 r2 Person object (name= Bob ) p2 = 73; r2.name= Steve ; P1 (50) P2 (73) r1 r2 Person object (name= Steve ) So we have primitive types and reference types. A variable for a primitive type can be thought of as being an instance of a type, so each you assign something to it, the same bit of memory gets changed as with P1 and P2 in the above slide. A variable for a reference type holds the memory address. If you assign something to it, what it used to be assigned to still exists in memory (but your variable doesn t link to it any more). Multiple variables can reference the same object in memory (like r1 and r2 above).

29 Q5. Draw box diagrams like the one above to illustrate what happens in each step of the following Java code in memory: Person p = null; Person p2 = new Person(); p = p2; p2 = new Person(); p=null; Pass By Value and By Reference void myfunction(int x, Person p) { x=x+1; p.name= Alice ; void static main(string[] arguments) { int num=70; Person person = new Person(); person.name= Bob ; myfunction(num, p); System.out.println(num+ +person.name) A. 70 Bob B. 70 Alice C. 71 Bob D. 71 Alice Now things are getting a bit more involved. We have added a function prototype into the mix: void myfunction(int x, Person p). This means it returns nothing (codenamed void) but takes an int and a Person object as input. When the function is run, the computer takes a copy of the inputs and creates local variables x and p to hold the copies.

30 Here s the thing: if you copy a primitive type, the value gets copied across (so if we were watching memory we would see two integers in memory, the second with the same value as the first). But for the reference type, it is the reference that gets copied and not the object it points to (i.e. we just create a new reference p and point it at the same object). When we copy a primitive value we say that it is pass by value. When we send a reference to the object rather than the object, it is pass by reference. In my opinion, this all gets a bit confusing in Java because you have no choice but to use references (unlike in, say C++). So I prefer to think of all variables as representing either primitives or references (rather than primitives and actual objects), and when we pass any variable around its value gets copied. The value of a primitive is its actual value, whilst the value of a reference is a memory address. You may or may not like this way of thinking: that s fine. Just make certain you understand the different treatment of primitives and reference types.

31 31

32 Chapter 2 Object-Oriented Concepts Modularity A class is a custom type We could just shove all our data into a class The real power of OOP is when a class corresponds to a concept E.g. a class might represent a car, or a person Note that there might be sub-concepts here A car has wheels: a wheel is a concept that we might want to embody in a separate class itself The basic idea is to figure out which concepts are useful, build and test a class for each one and then put them all together to make a program The really nice thing is that, if we've done a good job, we can easily re-use the classes we have specified again in other projects that have the same concepts. Modularity

33 Modularity is extremely important in OOP. It s the usual CS trick: break big problems down into chunks and solve each chunk. In this case, we have large programs, meaning scope for lots of coding bugs. We split the program into modules. The goal is: Modules are conceptually easier to handle Different people can work on different modules simultaneously Modules may be re-used in other software projects Modules can be individually tested as we go (unit testing) The module unit in OOP is a class. State and Behaviour An object/class has: State Properties that describe that specific instance E.g. colour, maximum speed, value Behaviour/Functionality Things that it can do These often mutate the state E.g. accelerate, brake, turn

34 Identifying Classes We want our class to be a grouping of conceptuallyrelated state and behaviour One popular way to group is using English grammar Noun Object Verb Method The footballer kicked the ball Representing a Class Graphically (UML) MyFancyClass - means private access - age : int + SetAge(age: int) : void State Behaviour + means public access

35 The has-a Association College * Student Arrow going left to right says a College has zero or more students Arrow going right to left says a Student has exactly 1 College What it means in real terms is that the College class will contain a variable that somehow links to a set of Student objects, and a Student will have a variable that references a College object. Note that we are only linking classes: we don't start drawing arrows to primitive types. The graphical notation used here is part of UML (Unified Modeling Language). UML is basically a standardised set of diagrams that can be used to describe software independently of any programming language used to create it. UML contains many different diagrams (touched on in the Software Design course). Here we just use the UML class diagram such as the one in the slide.

36 Anatomy of an OOP Program (Java) Class name public class MyFancyClass { public int somenumber; public String sometext; public void somemethod() { public static void main(string[] args) { MyFancyClass c = new MyFancyClass(); Class state (properties that an object has such as colour or size) Class behaviour (actions an object can do) 'Magic' start point for the program (named main by convention) Create an object of type MyFancyClass in memory and get a reference to it There are a couple of interesting things to note for later discussion. Firstly, the word public is used liberally. Secondly, the main function is declared inside the class itself and as static. Finally there is the notation String[] which represents an array of String objects in Java. You will see arrays in the practicals.

37 Anatomy of an OOP Program (C++) Class name class MyFancyClass { public: int somenumber; public String sometext; void somemethod() { Class state Class behaviour ; 'Magic' start point for the program void main(int argc, char **argv) { MyFancyClass c; Create an object of type MyFancyClass This is here just so you can compare. The Java syntax is based on C/C++ so it s no surprise that there s a lot of similarities. This certainly eases the transition from Java to C++ (or vice-versa), but there are a lot of pitfalls to bear in mind (mostly related to memory management).

38 Let's Build up Java Ourselves We'll start with a simple language that looks like Java and evolve it towards real Java Use the same primitives and Java and the similar syntax. E.g. class MyFancyClass { int somenumber; String sometext; void somemethod() { void main() { MyFancyClass c = new MyFancyClass(); A red box on the code box means it is not valid Java.

39 2.1 Encapsulation Encapsulation class Student { int age; void main() { Student s = new Student(); s.age = 21; Student s2 = new Student(); s2.age=-1; Student s3 = new Student(); s3.age=10055; Here we create 3 Student objects when our program runs Problem is obvious: nothing stops us (or anyone using our Student class) from putting in garbage as the age Let's add an access modifier that means nothing outside the class can change the age Encapsulation class Student { private int age; boolean SetAge(int a) { if (a>=0 && a<130) { age=a; return true; return false; int GetAge() {return age; Now nothing outside the class can access the age variable directly Have to add a new method to the class that allows age to be set (but only if it is a sensible value) Also needed a GetAge() method so external objects can find out the age. void main() { Student s = new Student(); s.setage(21);

40 Encapsulation We hid the state implementation to the outside world (no one can tell we store the age as an int without seeing the code), but provided mutator methods to... errr, mutate the state This is data encapsulation We define interfaces to our objects without committing long term to a particular implementation Advantages We can change the internal implementation whenever we like so long as we don't change the interface other than to add to it (E.g. we could decide to store the age as a float and add GetAgeFloat()) Encourages us to write clean interfaces for things to interact with our objects Another name for encapsulation is information hiding. The basic idea is that a class should expose a clean interface that allows interaction, but nothing about its internal state. So the general rule is that all state should start out as private and only have that access relaxed if there is a very, very good reason. Encapsulation helps to minimise coupling between classes. High coupling between two class, A and B, implies that a change in A is likely to ripple through to B. In a large software project, you really don t want a change in one class to mean you have to go and fix up the other 200 classes! So we strive for low coupling. It s also related to cohesion. A highly cohesive class contains only a set of strongly related functions rather than being a hotch-potch of functionality. We strive for high cohesion.

41 2.2 Inheritance Inheritance class Student { public int age; public String name; public int grade; class Lecturer { public int age; public String name; public int salary; There is a lot of duplication here Conceptually there is a hierarchy that we're not really representing Both Lecturers and Students are people (no, really). We can view each as a kind of specialisation of a general person They have all the properties of a person But they also have some extra stuff specific to them (I should not have used public variables here, but I did it to keep things simple) Inheritance class Person { public int age; Public String name; class Student extends Person { public int grade; class Lecturer extends Person { public int salary; We create a base class (Person) and add a new notion: classes can inherit properties from it Both state and functionality We say: Person is the superclass of Lecturer and Student Lecturer and Student subclass Person

42 Unfortunately, we tend to use an array of different names for things in an inheritance tree. For A extends B, you might get any of: A is the superclass of B A is the parent of B A is the base class of B B is a subclass of A B is the child of A B derives from A B inherits from A B subclasses A Representing Inheritance Graphically Person Also known as an is-a relation As in Student is-a Person Student Lecturer

43 Overriding Functionality We might want to require that every Person can dance. But the way a Lecturer dances is not likely to be the same as the way a Student dances... Student overrides the default class Person { public void dance() { jiggle_a_bit(); class Student extends Person { public void dance() { body_pop(); class Lecturer extends Person { Person defines a 'default' implementation of dance() Lecturer just inherits the default implementation 2.3 Abstract Classes Abstract Methods class Person { public void dance(); class Student extends Person { public void dance() { body_pop(); class Lecturer extends Person { public void dance() { jiggle_a_bit(); There are times when we have a definite concept but we expect every specialism of it to have a different implementation. We want to enforce that without providing a default E.g. We want to enforce that all objects that are Persons support a dance() method But we don't now think that there's a default dance() We specify an abstract dance method in the Person class i.e. we don't fill in any implementation (code) at all in Person.

44 Abstract Classes Before we could write Person p = new Person() But now p.dance() is undefined Therefore we have implicitly made the class abstract ie. It cannot be directly instantiated to an object Languages require some way to tell them that the class is meant to be abstract and it wasn't a mistake: public abstract class Person { public abstract void dance(); Java class Person { public: virtual void dance()=0; C++ Note that an abstract class can contain state variables that get inherited as normal Note also that, in Java, we can declare a class as abstract despite not specifying an abstract method in it!! Representing Abstract Classes Person + dance() Italics indicate the class or method is abstract Student Lecturer + dance() + dance()

45 2.4 Polymorphic Functions (Subtype) Polymorphism As we descend our inheritance tree we specialise by adding more detail ( a salary variable here, a dance() method there) So, in some sense, a Student object has all the information we need to make a Person (and some extra). It turns out to be quite useful to group things by their common ancestry in the inheritance tree We can do that semantically by expressions like: Student s = new Student(); Person p = (Person)s; This is a widening conversion (we move up the tree, increasing generality: always OK) Person p = new Person(); Student s = (Student)p; x This would be a narrowing conversion (we try to move down the tree, but it's not allowed here because the real object doesn't have all the info to be a Student) When we write (Person)s we say we are casting the Student object to a Person object. It might look a bit odd, but just remember that going down an inheritance tree adds stuff. Every object has an intrinsic type when we create it and it can t be cast to anything below that type (because it doesn t contain the extra stuff).

46 (Subtype) Polymorphism Student s = new Student(); Person p = (Person)s; p.dance(); Assuming Person has a default dance() method, what should happen here?? Option 1 Compiler says p is of type Person So p.dance() should do the default dance() action in Person Polymorphic behaviour Option 2 Compiler says The object in memory is really a Student So p.dance() should run the Student dance() method The Canonical Example Circle + draw() Square + draw() Oval + draw() A drawing program that can draw circles, squares, ovals and stars It would presumably keep a list of all the drawing objects Option 1 Keep a list of Circle objects, a list of Square objects,... Iterate over each list drawing each object in turn What has to change if we want to add a new shape? Star + draw()

47 The Canonical Example Shape Circle + draw() Square + draw() Oval + draw() Star + draw() Option 2 Keep a single list of Shape references Figure out what each object really is, narrow the reference and then draw() For every Shape s in myshapelist If (s is really a Circle) Circle c = (Circle)s; c.draw(); Else if (s is really a Square) Square sq = (Square)s; sq.draw(); Else if... What if we want to add a new shape? The Canonical Example Shape - x_position: int - y_position: int + draw() Circle + draw() Square + draw() Option 3 (Polymorphic) Keep a single list of Shape references Let the compiler figure out what to do with each Shape reference For every Shape s in myshapelist s.draw(); Oval + draw() Star + draw() What if we want to add a new shape?

48 Implementations Java All methods are polymorphic. Full stop. C++ Only functions marked virtual are polymorphic Polymorphism is an extremely important concept that you need to make sure you understand Interfaces Multiple Inheritance Student StudentLecturer Lecturer What if we have a Lecturer who studies for another degree? If we do as shown, we have a bit of a problem StudentLecturer inherits two different dance() methods So which one should it use if we instruct a StudentLecturer to dance()? The Java designers felt that this kind of problem mostly occurs when you have designed your class hierarchy badly Their solution? You can only extend (inherit) from one class in Java (which may itself inherit from another...) This is a Java oddity (C++ allows multiple class inheritance)

49 Interfaces (Java only) Java has the notion of an interface which is like a class except: There is no state whatsoever All methods are abstract For an interface, there can then be no clashes of methods or variables to worry about, so we can allow multiple inheritance <<interface>> Drivable + turn() + brake() <<interface>> Identifiable + getidentifier() Interface Drivable { public void turn(); public void brake(); Interface Identifiable { public void getidentifier(); abstract assumed for interfaces Bicycle + turn() + brake() Car + turn() + brake() + getidentifier() class Bicycle implements Drivable { public void turn() {... public void brake() { class Car implements Drivable, Identifiable { public void turn() {... public void brake() { Public void getidentifier() {... Q6. Explain the differences between a class, an abstract class and an interface. Q7. * Imagine you have two classes: Employee (which represents being an employee) and Ninja (which represents being a Ninja). An Employee has both state and behaviour; a Ninja has only behaviour. You need to represent an employee who is also a ninja. By creating only one interface and only one class(ninjaemployee), show how you can do this without having to copy method implementation code from either of the original classes.

50 Recap Important OOP concepts you need to understand: Modularity (classes, objects) Data Encapsulation Inheritance Abstraction Polymorphism 2.6 Lifecycle of an Object Constructors MyObject m = new MyObject(); You will have noticed that the RHS looks rather like a function call Every Class has a constructor, which is a function that gets run automatically whenever you create an object Allows you to initialise the object No constructor specified? You'll get the default constructor (which is empty). Multiple constructors specified? Each constructor must have a different signature (i.e. a different set of arguments) The compiler looks at the arguments you give in your new command and runs the appropriate one.

51 Constructor Chaining When you construct an object of a type with parent classes, we call the constructors of all of the parents in sequence Student s = new Student(); Animal 1. Call Animal() Person 2. Call Person() Student 3. Call Student() Q8. Write a Java program that demonstrates the notion of constructor chaining.

52 Destructors Most OO languages have a notion of a destructor too Gets run when the object is destroyed Allows us to release any resources (open files, etc) or memory that we might have created especially for the object class FileReader { public: FileReader() { f = fopen( myfile, r ); ~FileReader() { fclose(f); private : FILE *file; Cleaning Up A typical program creates lots of objects, not all of which need to stick around all the time Approach 1: Allow the programmer to specify when objects should be deleted from memory Lots of control, but what if they forget to delete an object? Approach 2: Delete the objects automatically (Garbage collection) But how do you know when an object is finished with?

53 Cleaning Up (Java) Java reference counts. i.e. it keeps track of how many references point to a given object. If there are none, the programmer can't access that object ever again so it can be deleted Person object #ref = 2 Person object #ref = 0 Deletable r1 r2 r1 = null; r2 = null; r1 r2 Cleaning Up (Java) Good: System cleans up after us Bad: It has to keep searching for objects with no references. This requires effort on the part of the CPU so it degrades performance. We can't easily predict when an object will be deleted

54 Cleaning Up (Java) So we can't tell when a destructor would run so Java doesn't have them!! It does have the notion of a finalizer that gets run when an object is garbage collected BUT there's no guarantee an object will ever get garbage collected in Java... Garbage Collection!= Destruction 2.7 Class-Level Data Class-Level Data and Functionality public class ShopItem { private float price; private float VATRate = 0.175; public float GetSalesPrice() { return price*(1.0+vatrate); public void SetVATRate(float rate) { VATRate=rate; Imagine we have a class ShopItem. Every ShopItem has an individual core price to which we need to add VAT Two issues here: 1. If the VAT rate changes, we need to find every ShopItem object and run SetVATRate(...) on it. We could end up with different items having different VAT rates when they shouldn't It is inefficient. Every time we create a new ShopItem object, we allocate another 32 bits of memory just to store exactly the same number! What we have is a piece of information that is class-level not object level Each individual object has the same value at all times We throw in the static keyword: public class ShopItem { private float price; private static float VATRate;... Variable created only once and has the lifetime of the program, not the object

55 Class-Level Data and Functionality We now have one place to update More efficient memory usage Can also make methods static too A static method must be instance independent i.e. it can't rely on member variables in any way Sometimes this is obviously needed. E.g public class Whatever { public static void main(string[] args) {... Must be able to run this function without creating an object of type Whatever (which we would have to do in the main()..!) Why use other static functions? A static function is like a function in ML it can depend only on its arguments Easier to debug (not dependent on any state) Self documenting Allows us to group related methods in a Class, but not require us to create an object to run them The compiler can produce more efficient code since no specific object is involved public class Math { public float sqrt(float x) { public double sin(float x) { public double cos(float x) { Math mathobject = new Math(); mathobject.sqrt(9.0);... vs public class Math { public static float sqrt(float x) { public static float sin(float x) { public static float cos(float x) { Math.sqrt(9.0);...

56 2.8 Examples One of the examples we will develop in class is a representation of a two dimensional vector (x, y). This is obviously a very simple class, but it brings us to an interesting question of mutability. An immutable class cannot have its state changed after it has been created (you re familiar with this from ML, where everything is immutable). A mutable class can be altered somehow (usually as a side effect of calling a method). To make a class immutable: Make sure all state is private. Consider making state final (this just tells the compiler that the value never changes once constructed). Make sure no method tries to change any internal state. Some advantages of immutability: Simpler to contruct, test and use Automatically thread safe (don t worry if this means nothing to you yet). Allows lazy instatiation of objects. In fact, to quote Effective Java by Joshua Bloch: Classes should be immutable unless there s a very good reason to make them mutable... If a class cannot be made immutable, limit its mutability as much as possible.

57 Q9. Modify the Vector2D class to handle subtraction and scalar product. Q10. Is the Vector2D class developed in lectures mutable or immutable? Q11. Vector2D provides a method to add two vectors. Contrast the following approaches to providing an add method assuming Vector2D is (i) mutable, and (ii) immutable. (a) public void add(vector2d v) (b) public Vector2D add(vector2d v) (c) public Vector2D add(vector2d v1, Vector2D v2) (d) public static Vector2D add(vector2d v1, Vector2D v2) Q12. A student wishes to create a class for a 3D vector and chooses to derive from the Vector2D class (i.e. public void Vector3D extends Vector2D). The argument is that a 3D vector is a 2D vector with some stuff added. Explain the conceptual misunderstanding here. Q13. Explain how to write a Java program that is functional in nature i.e. no modifiable variables, methods are mathematical functions without side effects. Remember the final keyword.

58 58

59 Chapter 3 Java Miscellany 3.1 Copying or Cloning Java Objects Cloning Sometimes we really do want to copy an object Person object (name = Bob ) Person object (name = Bob ) Person object (name = Bob ) r r r_copy Java calls this cloning We need special support for it

60 Cloning Every class in Java ultimately inherits from the Object class The Object class contains a clone() method So just call this to clone an object, right? Wrong! Surprisingly, the problem is defining what copy actually means Cloning public class MyClass { private float price = 77; MyClass object (price=77) Clone MyClass object (price=77) MyClass object (price=77)

61 Shallow and Deep Copies public class MyClass { private MyOtherClass moc; MyClass object MyClass object MyClass object Shallow MyOtherClass object MyOtherClass object Deep MyClass object MyClass object MyOtherClass object MyOtherClass object Java Cloning So do you want shallow or deep? The default implementation of clone() performs a shallow copy But Java developers were worried that this might not be appropriate: they decided they wanted to know for sure that we'd thought about whether this was appropriate Java has a Cloneable interface If you call clone on anything that doesn't extend this interface, it fails

62 Marker Interfaces If you go and look at what's in the Cloneable interface, you'll find it's empty!! What's going on? Well, the clone() method is already inherited from Object so it doesn't need to specify it This is an example of a Marker Interface A marker interface is an empty interface that is used to label classes This approach is found occasionally in the Java libraries You might also see these marker interfaces referred to as tag interfaces. They are simply a way to label or tag a class. They can be very useful, but equally they can be a pain (you can t dynamically tag a class, nor can you prevent a tag being inherited by all subclasses).

Object Oriented Programming Dr Robert Harle. IA NST CS and CST Lent 2009/10 Handout 1

Object Oriented Programming Dr Robert Harle. IA NST CS and CST Lent 2009/10 Handout 1 Object Oriented Programming Dr Robert Harle IA NST CS and CST Lent 2009/10 Handout 1 OO Programming This is a new course this year that absorbs what was Programming Methods and provides a more formal look

More information

The high-level language has a series of primitive (builtin) types that we use to signify what s in the memory

The high-level language has a series of primitive (builtin) types that we use to signify what s in the memory Types and Variables We write code like: int x = 512; int y = 200; int z = x+y; The high-level language has a series of primitive (builtin) types that we use to signify what s in the memory The compiler

More information

Error Handling. public int divide(double a, double b) { if (b==0) return -1; // error double result = a/b; return 0; // success }

Error Handling. public int divide(double a, double b) { if (b==0) return -1; // error double result = a/b; return 0; // success } Exceptions Error Handling You do a lot on this in your practicals, so we'll just touch on it here The traditional way of handling errors is to return a value that indicates success/failure/error public

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Note that this is essentially the same UML as the State pattern! The intent of each of the two patterns is quite different however:

Note that this is essentially the same UML as the State pattern! The intent of each of the two patterns is quite different however: Note that this is essentially the same UML as the State pattern! The intent of each of the two patterns is quite different however: State is about encapsulating behaviour that is linked to specific internal

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Chapter 17 vector and Free Store. Bjarne Stroustrup

Chapter 17 vector and Free Store. Bjarne Stroustrup Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

MITOCW watch?v=flgjisf3l78

MITOCW watch?v=flgjisf3l78 MITOCW watch?v=flgjisf3l78 The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

Lecture 02, Fall 2018 Friday September 7

Lecture 02, Fall 2018 Friday September 7 Anatomy of a class Oliver W. Layton CS231: Data Structures and Algorithms Lecture 02, Fall 2018 Friday September 7 Follow-up Python is also cross-platform. What s the advantage of Java? It s true: Python

More information

OOP Exercise Sheet 2013/14

OOP Exercise Sheet 2013/14 OOP Exercise Sheet 2013/14 Dr Robert Harle These exercises follow the notes and are intended to provide material for supervisions. They are graded A C to indicate the effort expected (An A would be worth

More information

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

Lecture Topics. Administrivia

Lecture Topics. Administrivia ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Chapter 6 Classes and Objects

Chapter 6 Classes and Objects Chapter 6 Classes and Objects Hello! Today we will focus on creating classes and objects. Now that our practice problems will tend to generate multiple files, I strongly suggest you create a folder for

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output CS61C L2 Number Representation & Introduction to C (1) insteecsberkeleyedu/~cs61c CS61C : Machine Structures Lecture #2 Number Rep & Intro to C Scott Beamer Instructor 2007-06-26 Review Continued rapid

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist In Handout 28, the Guide to Inductive Proofs, we outlined a number of specifc issues and concepts to be mindful about when

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style CS125 : Introduction to Computer Science Lecture Notes #4 Type Checking, Input/Output, and Programming Style c 2005, 2004, 2002, 2001, 2000 Jason Zych 1 Lecture 4 : Type Checking, Input/Output, and Programming

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2 CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,

More information

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

D Programming Language

D Programming Language Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take

More information

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng Slide Set 2 for ENCM 335 in Fall 2018 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2018 ENCM 335 Fall 2018 Slide Set 2 slide

More information

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 2: Review of Object Orientation 2.1 What is Object Orientation? Procedural paradigm: Software is organized

More information

Vector and Free Store (Pointers and Memory Allocation)

Vector and Free Store (Pointers and Memory Allocation) DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space.

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space. 1 All programming languages provide abstractions. Assembly language is a small abstraction of the underlying machine. Many imperative languages (FORTRAN, BASIC, and C) are abstractions of assembly language.

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Pointers and Memory 1

Pointers and Memory 1 Pointers and Memory 1 Pointer values Pointer values are memory addresses Think of them as a kind of integer values The first byte of memory is 0, the next 1, and so on A pointer p can hold the address

More information

Pointers in C/C++ 1 Memory Addresses 2

Pointers in C/C++ 1 Memory Addresses 2 Pointers in C/C++ Contents 1 Memory Addresses 2 2 Pointers and Indirection 3 2.1 The & and * Operators.............................................. 4 2.2 A Comment on Types - Muy Importante!...................................

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

(Refer Slide Time: 4:00)

(Refer Slide Time: 4:00) Principles of Programming Languages Dr. S. Arun Kumar Department of Computer Science & Engineering Indian Institute of Technology, Delhi Lecture - 38 Meanings Let us look at abstracts namely functional

More information

Lecture 1: Overview

Lecture 1: Overview 15-150 Lecture 1: Overview Lecture by Stefan Muller May 21, 2018 Welcome to 15-150! Today s lecture was an overview that showed the highlights of everything you re learning this semester, which also meant

More information

Contents. Slide Set 1. About these slides. Outline of Slide Set 1. Typographical conventions: Italics. Typographical conventions. About these slides

Contents. Slide Set 1. About these slides. Outline of Slide Set 1. Typographical conventions: Italics. Typographical conventions. About these slides Slide Set 1 for ENCM 369 Winter 2014 Lecture Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary Winter Term, 2014 ENCM 369 W14 Section

More information

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology. Guide to and Hi everybody! In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology. This guide focuses on two of those symbols: and. These symbols represent concepts

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

CS103 Spring 2018 Mathematical Vocabulary

CS103 Spring 2018 Mathematical Vocabulary CS103 Spring 2018 Mathematical Vocabulary You keep using that word. I do not think it means what you think it means. - Inigo Montoya, from The Princess Bride Consider the humble while loop in most programming

More information

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between MITOCW Lecture 10A [MUSIC PLAYING] PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between all these high-level languages like Lisp and the query

More information

OOP Design Conclusions and Variations

OOP Design Conclusions and Variations CS108, Stanford Handout #20 Fall, 2008-09 Osvaldo Jiménez OOP Design Conclusions and Variations Thanks to Nick Parlante for much of this handout Part 1 -- Mainstream OOP Design First, we have the standard,

More information

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley. CS61C Machine Structures Lecture 3 Introduction to the C Programming Language 1/23/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L03 Introduction to C (1) Administrivia

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

Designing Robust Classes

Designing Robust Classes Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations

More information

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions. Handout 2 Functions, Lists, For Loops and Tuples [ ] Functions -- parameters/arguments, "calling" functions, return values, etc. Please make sure you understand this example: def square(x): return x *

More information

05. SINGLETON PATTERN. One of a Kind Objects

05. SINGLETON PATTERN. One of a Kind Objects BIM492 DESIGN PATTERNS 05. SINGLETON PATTERN One of a Kind Objects Developer: What use is that? Guru: There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle

More information

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

More information

Kickstart Intro to Java Part I

Kickstart Intro to Java Part I Kickstart Intro to Java Part I COMP346/5461 - Operating Systems Revision 1.6 February 9, 2004 1 Topics Me, Myself, and I Why Java 1.2.*? Setting Up the Environment Buzz about Java Java vs. C++ Basic Java

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information

Functions and Decomposition

Functions and Decomposition Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the

More information

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation Object-Oriented Software Engineering Chapter 2: Review of Object Orientation 2.1 What is Object Orientation? Procedural paradigm: Software is organized around the notion of procedures Procedural abstraction

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using

More information

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics Dan Grossman Spring 2011 Review e ::= λx. e x e e c v ::= λx. e c τ ::= int τ τ Γ ::= Γ, x : τ (λx. e) v e[v/x] e 1 e 1 e 1 e

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Types, Expressions, and States

Types, Expressions, and States 8/27: solved Types, Expressions, and States CS 536: Science of Programming, Fall 2018 A. Why? Expressions represent values in programming languages, relative to a state. Types describe common properties

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

CS 177 Recitation. Week 1 Intro to Java

CS 177 Recitation. Week 1 Intro to Java CS 177 Recitation Week 1 Intro to Java Questions? Computers Computers can do really complex stuff. How? By manipulating data according to lists of instructions. Fundamentally, this is all that a computer

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 1 Date:

More information

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=0jljzrnhwoi MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015 COMP-202: Foundations of Programming Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015 Assignment Due Date Assignment 1 is now due on Tuesday, Jan 20 th, 11:59pm. Quiz 1 is

More information

Starting to Program in C++ (Basics & I/O)

Starting to Program in C++ (Basics & I/O) Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

CS 251 Intermediate Programming Java Basics

CS 251 Intermediate Programming Java Basics CS 251 Intermediate Programming Java Basics Brooke Chenoweth University of New Mexico Spring 2018 Prerequisites These are the topics that I assume that you have already seen: Variables Boolean expressions

More information

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O Introduction The WRITE and READ ADT Operations Case Studies: Arrays Strings Binary Trees Binary Search Trees Unordered Search Trees Page 1 Introduction

More information

Type Checking in COOL (II) Lecture 10

Type Checking in COOL (II) Lecture 10 Type Checking in COOL (II) Lecture 10 1 Lecture Outline Type systems and their expressiveness Type checking with SELF_TYPE in COOL Error recovery in semantic analysis 2 Expressiveness of Static Type Systems

More information