Object Oriented Programming Dr Robert Harle. Java Ticks. OO Programming

Size: px
Start display at page:

Download "Object Oriented Programming Dr Robert Harle. Java Ticks. OO Programming"

Transcription

1 Object Oriented Programming Dr Robert Harle IA NST CS and CST Lent 2009/10 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 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 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 If we teach Java in isolation, there s a good chance that students don t manage to mentally separate the object-oriented concepts from 1 2

2 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 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. 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 3 4

3 What can Computers Do? 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) λ 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. 5 6

4 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). 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. 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. 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 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. 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. 7 8

5 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. Dumb Model of a Computer Memory L6X L7Y AXYZ SZ CPU Registers P 1 X 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. Y Z ALU 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 follows loads in two numbers and adds them. Those doing the Operating Systems course will realise this is just the fetch-execute 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: Dumb Model of a Computer Memory L6X L7Y AXYZ SZ CPU Registers P 2 X 63 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 Y Z ALU 9 10

6 Dumb Model of a Computer Memory (RAM) Memory L6X L7Y AXYZ SZ Memory Registers CPU 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 P X Y Z ALU 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 Dumb Model of a Computer Memory L6X L7Y AXYZ SZ CPU 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. Registers P 4 X Y Z ALU Q1. How much system memory can we use if we have 8, 32 or 64 bit registers? All a computer does is execute instruction after instruction. Never forget this when programming! 11 12

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

8 1.2 Functional and Imperative Revisited 1.3 Machine Architectures 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 in an imperative language, 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. 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 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. Binary executable for PC (x86) Binary executable for ARM 15 16

9 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? 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 were no machines capable of directly using bytecode, but recently they have started to appear in niche areas. For the most part, however, you use a virtual machine. This is a piece of software that has been compiled specifically for your architecture (like most off-the-shelf software) and which acts an an interpreter, converting 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:

10 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 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 every 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. 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] 19 20

11 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 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 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 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: 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 public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World"); 21 22

12 1.5 Pointers and References 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. 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 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 x 23 24

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

14 In Java, the special value is signified using the keyword null: References MyClass m = null;... m = new MyClass(); // Not initialised 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 ) 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) {... p2 = 73; r2.name= Steve ; P1 (50) P2 (73) r1 r2 Person object (name= Steve ) 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. 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)

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

16 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 31 32

17 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) 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 The module unit in OOP is a class. State and Behaviour An object/class has: Representing a Class Graphically (UML) State Properties that describe that specific instance E.g. colour, maximum speed, value - age : int MyFancyClass State Behaviour/Functionality Things that it can do These often mutate the state E.g. accelerate, brake, turn - means private access + means public access + SetAge(age: int) : void Behaviour 33 34

18 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. Anatomy of an OOP Program (Java) public class MyFancyClass { public int somenumber; public String sometext; public void somemethod() { Class name 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 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. 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

19 Anatomy of an OOP Program (C++) class MyFancyClass { public: ; int somenumber; public String sometext; void somemethod() { Class name void main(int argc, char **argv) { MyFancyClass c; Class state Class behaviour 'Magic' start point for the program 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() { Create an object of type MyFancyClass void main() { MyFancyClass c = new MyFancyClass(); This is here just so you can compare. The Java syntax is based on C/C++ so it s no surprise that there are 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). A red box on the code box means it is not valid Java

20 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 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 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; void main() { Student s = new Student(); s.setage(21); 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. 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

21 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 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 (I should not have used public variables here, but I did it to keep things simple) Person Inheritance Also known as an is-a relation As in Student is-a Person 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 Student Lecturer For reasons I don t understand, many students seem to confuse is-a and has-a arrows in their UML class diagrams: please make sure you don t! 41 42

22 Casting/Conversions 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; Person p = new Person(); Student s = (Student)p; x This is a widening conversion (we move up the tree, increasing generality: always OK) 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) Inheritance and State Variables + Inheritance class Person { public String mname; protected int mage; private double mheight; class Student extends Person { public void do_something() { mname= Bob ; mage=70; mheight=1.70; Student inherits this as a public variable and so can access it Student inherits this as a protected variable and so can access it Student inherits this as a private variable and so cannot access it When we write (Person)s we often 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). Variables + Inheritance: Shadowing class A { public int x; class B extends A { public int x; class C extends B { public int x; public void action() { // Ways to set the x in C x = 10; this.x = 10; In memory, you will find three allocated integers for every object of type C. We say that variables in parent classes with the same name as those in child classes are shadowed. Note that the variables are being shadowed: i.e. nothing is being replaced. This is contrast to the behaviour with methods... // Ways to set the x in B super.x = 10; ((B)this).x = 10; // Ways to set the x in A ((A)this.x = 10; 43 44

23 There are two new keywords that have appeared here: super and this. The this keyword can be used in any class method 1 and provides us with a reference to the current object. In fact, the this keyword is what you need to access anything within a class, but because we d end up writing this all over the place, it is taken as implicit. So, for example: Inheritance and Functionality Methods + Inheritance: Overriding 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... public class A { private int x; public void go() { this.x=20; 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 and jiggles becomes: public class A { private int x; public void go() { x=20; (Subtype) Polymorphism Student s = new Student(); Person p = (Person)s; p.dance(); Assuming Person has a default dance() method, what should happen here?? The super keyword gives us access to the direct parent. You ll meet both in your Java practicals. 1 By this I mean it cannot be used outside of a class, such as within a static method: see later for an explanation of these. Option 1 Compiler says p is of type Person So p.dance() should do the default dance() action in Person Option 2 Compiler says The object in memory is really a Student So p.dance() should run the Student dance() method Polymorphic behaviour 45 46

24 Option 1 would match our expectations from shadowing: the idea that the object contains two dance() methods, and we can choose between them. Option 2 (called polymorphic) effectively has the parent method replaced by the child method. It turns out that option 2 is immensely useful and so is the way Java went. However, not all OO languages choose between the options. C++, for example, allows you to choose: #include <iostream> class A { public: void printnormal() { std::cout << "A" << std::endl; virtual void printvirtual() { std::cout << "A" << std::endl; ; class B : public A { public: void printnormal() { std::cout << "B" << std::endl; ; int main(int argc, char ** argv) { B bobj; // Declare an object of type B. // Set up pointers in C++ B *bptr = &bobj; A *aptr = (A*)bptr; // Cast bptr->printnormal(); aptr->printnormal(); bptr->printvirtual(); aptr->printvirtual(); Which results in: B A B B i.e. you need to add a special tag (virtual) to the methods that you want to behave polymorphically in C++. virtual void printvirtual() { std::cout << "B" << std::endl; 47 48

25 The Canonical Example The Canonical Example Circle + draw() Square + draw() Oval + draw() Star 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? Shape - x_position: int - y_position: int + draw() Circle + draw() Square + draw() Oval + draw() Star 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(); What if we want to add a new shape? + draw() + draw() The Canonical Example Implementations Shape Circle Option 2 Keep a single list of Shape references Figure out what each object really is, narrow the reference and then draw() Java All methods are polymorphic. Full stop. Python All methods are polymorphic. C++ Only functions marked virtual are polymorphic + draw() Square + draw() Oval + draw() Star + 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? Polymorphism is an extremely important concept that you need to make sure you understand... What happens when you run a polymorphic function is that the system must dynamically decide which version to run. As you might 49 50

26 expect, this isn t instantaneous and so there is an overhead associated with using polymorphic functions. This can be an advantage of languages like C++ (which give you the choice), but more and more languages seem to favour simplicity over power, and this choice is one of the first things to go! 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: 2.3 Abstract Classes public abstract class Person { public abstract void dance(); Java class Person { public: virtual void dance()=0; C++ 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 (like the draw() method in the Shape example). We want to enforce that idea without providing a default method 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. 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!! Depending on who you re talking to, you ll find different terminology for the initial declaration of the abstract function (e.g. the public abstract void dance() bit). Common terms include method prototype and method stub. An abstract method can be thought of as a contractual obligation: any non-abstract class that inherits from this class will have that method implemented

27 Representing Abstract Classes Student + dance() Person + dance() Lecturer + dance() Italics indicate the class or method is abstract 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() Bicycle + turn() + brake() <<interface>> Identifiable + getidentifier() Car + turn() + brake() + getidentifier() Interface Drivable { public void turn(); public void brake(); Interface Identifiable { public void getidentifier(); class Bicycle implements Drivable { public void turn() {... public void brake() { abstract assumed for interfaces class Car implements Drivable, Identifiable { public void turn() {... public void brake() { Public void getidentifier() { 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) 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

28 Recap Important OOP concepts you need to understand: Modularity (classes, objects) Data Encapsulation Inheritance Abstraction Polymorphism The return we expect is obviously a reference to the newly created object, which the compiler sorts out for us. Examples public class Person { private String mname; // Constructor public Person(String name) { mname=name; public static void main(string[] args) { Person p = new Person( Bob ); class Person { private: std::string mname; public: Person(std::string &name) { mname=name; ; int main(int argc, char ** argv) { Person p ( Bob ); Java C Lifecycle of an Object Constructors Default Constructor MyObject m = new MyObject(); You will have noticed that the RHS looks rather like a function call, and that's exactly what it is. It's a method that gets called when the object is constructed, and it goes by the name of a constructor (it's not rocket science). public class Person { private String mname; public static void main(string[] args) { Person p = new Person(); If you specify no constructor at all, the Java fills in an empty one for you The default constructor takes no arguments We use constructors to initialise the state of the class in a convenient way. A constructor has the same name as the class A constructor has no return type specified 55 56

29 Beware: As soon as you specify any constructor whatsoever, Java won t add in a default constructor... Multiple Constructors public class Student { private String mname; private int mscore; public Student(String s) { mname=s; mscore=0; public Student(String s, int sc) { mname=s; mscore=sc; public static void main(string[] args) { Student s1 = new Student("Bob"); Student s2 = new Student("Bob",55); You can specify as many constructors as you like. Each constructor must have a different signature (argument list) What actually happens is that the first line of a constructor always starts with super(), which is a call to the parent constructor (which itself starts with super(), etc.). If it does not, the compiler adds one for you: public class Person { public Person() { becomes: 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(); public class Person { public Person() { super(); This can get messy though: what if the parent does not have a default constructor? In this case, the code won t compile, and we will have to manually add a call to super ourselves, using the appropriate arguments. E.g. Animal Person Student 1. Call Animal() 2. Call Person() 3. Call Student() public class Person { protected String mname; public Person(String name) { mname=name; 57 58

30 public class Student extends Person { private int mscore; public Student (String name, int score) { super(name); mscore = score; Q8. Write a Java program that demonstrates constructor chaining in action. 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 if the programmer doesn't explicitly tell you it is? 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 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 class FileReader { public: // Constructor FileReader() { f = fopen( myfile, r ); // Destructor ~FileReader() { fclose(f); private : FILE *file; int main(int argc, char ** argv) { // Construct a FileReader Object FileReader *f = new FileReader(); // Use object here... // Destruct the object delete f; C++ Person object #ref = 2 r1 r2 r1 = null; r2 = null; Person object #ref = 0 r1 r2 Deletable 59 60

Java Interview Questions and Answers

Java Interview Questions and Answers 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 and compile the java

More information

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1 The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Chapter 1 Fundamentals of Java Programming

Chapter 1 Fundamentals of Java Programming Chapter 1 Fundamentals of Java Programming Computers and Computer Programming Writing and Executing a Java Program Elements of a Java Program Features of Java Accessing the Classes and Class Members The

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014 CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages Nicki Dell Spring 2014 What is a Programming Language? A set of symbols and associated tools that translate (if necessary) collections

More information

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Chapter 7D The Java Virtual Machine

Chapter 7D The Java Virtual Machine This sub chapter discusses another architecture, that of the JVM (Java Virtual Machine). In general, a VM (Virtual Machine) is a hypothetical machine (implemented in either hardware or software) that directly

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper

More information

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings Object Calisthenics 9 steps to better software design today, by Jeff Bay http://www.xpteam.com/jeff/writings/objectcalisthenics.rtf http://www.pragprog.com/titles/twa/thoughtworks-anthology We ve all seen

More information

Python Loops and String Manipulation

Python Loops and String Manipulation WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

More information

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

University of Twente. A simulation of the Java Virtual Machine using graph grammars

University of Twente. A simulation of the Java Virtual Machine using graph grammars University of Twente Department of Computer Science A simulation of the Java Virtual Machine using graph grammars Master of Science thesis M. R. Arends, November 2003 A simulation of the Java Virtual Machine

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

Chapter 13: Program Development and Programming Languages

Chapter 13: Program Development and Programming Languages Understanding Computers Today and Tomorrow 12 th Edition Chapter 13: Program Development and Programming Languages Learning Objectives Understand the differences between structured programming, object-oriented

More information

The Java Virtual Machine and Mobile Devices. John Buford, Ph.D. buford@alum.mit.edu Oct 2003 Presented to Gordon College CS 311

The Java Virtual Machine and Mobile Devices. John Buford, Ph.D. buford@alum.mit.edu Oct 2003 Presented to Gordon College CS 311 The Java Virtual Machine and Mobile Devices John Buford, Ph.D. buford@alum.mit.edu Oct 2003 Presented to Gordon College CS 311 Objectives Review virtual machine concept Introduce stack machine architecture

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming Java has become enormously popular. Java s rapid rise and wide acceptance can be traced to its design

More information

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

02 B The Java Virtual Machine

02 B The Java Virtual Machine 02 B The Java Virtual Machine CS1102S: Data Structures and Algorithms Martin Henz January 22, 2010 Generated on Friday 22 nd January, 2010, 09:46 CS1102S: Data Structures and Algorithms 02 B The Java Virtual

More information

Part 1 Foundations of object orientation

Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed

More information

Variable Base Interface

Variable Base Interface Chapter 6 Variable Base Interface 6.1 Introduction Finite element codes has been changed a lot during the evolution of the Finite Element Method, In its early times, finite element applications were developed

More information

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For Projet Java Responsables: Ocan Sankur, Guillaume Scerri (LSV, ENS Cachan) Objectives - Apprendre à programmer en Java - Travailler à plusieurs sur un gros projet qui a plusieurs aspects: graphisme, interface

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Tutorial: Getting Started

Tutorial: Getting Started 9 Tutorial: Getting Started INFRASTRUCTURE A MAKEFILE PLAIN HELLO WORLD APERIODIC HELLO WORLD PERIODIC HELLO WORLD WATCH THOSE REAL-TIME PRIORITIES THEY ARE SERIOUS SUMMARY Getting started with a new platform

More information

No no-argument constructor. No default constructor found

No no-argument constructor. No default constructor found Every software developer deals with bugs. The really tough bugs aren t detected by the compiler. Nasty bugs manifest themselves only when executed at runtime. Here is a list of the top ten difficult and

More information

what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored?

what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored? Inside the CPU how does the CPU work? what operations can it perform? how does it perform them? on what kind of data? where are instructions and data stored? some short, boring programs to illustrate the

More information

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly

More information

Chapter 1 Java Program Design and Development

Chapter 1 Java Program Design and Development presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli Ralph Walde Trinity College Hartford, CT published by Prentice Hall Java, Java, Java Object Oriented

More information

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards Course Title: TeenCoder: Java Programming Course ISBN: 978 0 9887070 2 3 Course Year: 2015 Note: Citation(s) listed may represent

More information

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance Introduction to C++ January 19, 2011 Massachusetts Institute of Technology 6.096 Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance We ve already seen how to define composite datatypes

More information

Introduction to Software Paradigms & Procedural Programming Paradigm

Introduction to Software Paradigms & Procedural Programming Paradigm Introduction & Procedural Programming Sample Courseware Introduction to Software Paradigms & Procedural Programming Paradigm This Lesson introduces main terminology to be used in the whole course. Thus,

More information

How To Write Portable Programs In C

How To Write Portable Programs In C Writing Portable Programs COS 217 1 Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important

More information

CSC230 Getting Starting in C. Tyler Bletsch

CSC230 Getting Starting in C. Tyler Bletsch CSC230 Getting Starting in C Tyler Bletsch What is C? The language of UNIX Procedural language (no classes) Low-level access to memory Easy to map to machine language Not much run-time stuff needed Surprisingly

More information

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully.

More information

Club Accounts. 2011 Question 6.

Club Accounts. 2011 Question 6. Club Accounts. 2011 Question 6. Anyone familiar with Farm Accounts or Service Firms (notes for both topics are back on the webpage you found this on), will have no trouble with Club Accounts. Essentially

More information

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science Program Schedule CTech Computer Science Credits CS101 Computer Science I 3 MATH100 Foundations of Mathematics and

More information

CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

More information

Programming Methods & Java Examples

Programming Methods & Java Examples Programming Methods & Java Examples Dr Robert Harle, 2009 The following questions may be useful to work through for supervisions and/or revision. They are separated broadly by handout, but borders are

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities The classroom is set up like a traditional classroom on the left side of the room. This is where I will conduct my

More information

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship. CSCI 253 Object Oriented Design: Java Review OOP George Blankenship George Blankenship 1 Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation Abstract Data Type (ADT) Implementation

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111 Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages Corky Cartwright Swarat Chaudhuri November 30, 20111 Overview I In OO languages, data values (except for designated non-oo

More information

New Generation of Software Development

New Generation of Software Development New Generation of Software Development Terry Hon University of British Columbia 201-2366 Main Mall Vancouver B.C. V6T 1Z4 tyehon@cs.ubc.ca ABSTRACT In this paper, I present a picture of what software development

More information

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Developed By Brian Weinfeld Course Description: AP Computer

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Aspect-Oriented Programming

Aspect-Oriented Programming Aspect-Oriented Programming An Introduction to Aspect-Oriented Programming and AspectJ Niklas Påhlsson Department of Technology University of Kalmar S 391 82 Kalmar SWEDEN Topic Report for Software Engineering

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

Java Crash Course Part I

Java Crash Course Part I Java Crash Course Part I School of Business and Economics Institute of Information Systems HU-Berlin WS 2005 Sebastian Kolbe skolbe@wiwi.hu-berlin.de Overview (Short) introduction to the environment Linux

More information

Code Qualities and Coding Practices

Code Qualities and Coding Practices Code Qualities and Coding Practices Practices to Achieve Quality Scott L. Bain and the Net Objectives Agile Practice 13 December 2007 Contents Overview... 3 The Code Quality Practices... 5 Write Tests

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

What is a programming language?

What is a programming language? Overview Introduction Motivation Why study programming languages? Some key concepts What is a programming language? Artificial language" Computers" Programs" Syntax" Semantics" What is a programming language?...there

More information

Week 2 Practical Objects and Turtles

Week 2 Practical Objects and Turtles Week 2 Practical Objects and Turtles Aims and Objectives Your aim in this practical is: to practise the creation and use of objects in Java By the end of this practical you should be able to: create objects

More information

Chapter 1. Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705. CS-4337 Organization of Programming Languages

Chapter 1. Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705. CS-4337 Organization of Programming Languages Chapter 1 CS-4337 Organization of Programming Languages Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705 Chapter 1 Topics Reasons for Studying Concepts of Programming

More information

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Yosemite National Park, California. CSE 114 Computer Science I Inheritance Yosemite National Park, California CSE 114 Computer Science I Inheritance Containment A class contains another class if it instantiates an object of that class HAS-A also called aggregation PairOfDice

More information

[Refer Slide Time: 05:10]

[Refer Slide Time: 05:10] Principles of Programming Languages Prof: S. Arun Kumar Department of Computer Science and Engineering Indian Institute of Technology Delhi Lecture no 7 Lecture Title: Syntactic Classes Welcome to lecture

More information

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang 6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang Today s topics Why objects? Object-oriented programming (OOP) in C++ classes fields & methods objects representation

More information

CS193j, Stanford Handout #10 OOP 3

CS193j, Stanford Handout #10 OOP 3 CS193j, Stanford Handout #10 Summer, 2003 Manu Kumar OOP 3 Abstract Superclass Factor Common Code Up Several related classes with overlapping code Factor common code up into a common superclass Examples

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Once the schema has been designed, it can be implemented in the RDBMS.

Once the schema has been designed, it can be implemented in the RDBMS. 2. Creating a database Designing the database schema... 1 Representing Classes, Attributes and Objects... 2 Data types... 5 Additional constraints... 6 Choosing the right fields... 7 Implementing a table

More information

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding Compiling Object Oriented Languages What is an Object-Oriented Programming Language? Last time Dynamic compilation Today Introduction to compiling object oriented languages What are the issues? Objects

More information

Book 3 Cost Estimating in an Agile Development Environment. (early release)

Book 3 Cost Estimating in an Agile Development Environment. (early release) Book 3 Cost Estimating in an Agile Development Environment (early release) Book 3: Cost Estimating in an Agile Development Environment In this third book I ll use the slides I gave at a speech several

More information

Part I. Multiple Choice Questions (2 points each):

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

CSE 308. Coding Conventions. Reference

CSE 308. Coding Conventions. Reference CSE 308 Coding Conventions Reference Java Coding Conventions googlestyleguide.googlecode.com/svn/trunk/javaguide.html Java Naming Conventions www.ibm.com/developerworks/library/ws-tipnamingconv.html 2

More information

Programming Project 1: Lexical Analyzer (Scanner)

Programming Project 1: Lexical Analyzer (Scanner) CS 331 Compilers Fall 2015 Programming Project 1: Lexical Analyzer (Scanner) Prof. Szajda Due Tuesday, September 15, 11:59:59 pm 1 Overview of the Programming Project Programming projects I IV will direct

More information

GDB Tutorial. A Walkthrough with Examples. CMSC 212 - Spring 2009. Last modified March 22, 2009. GDB Tutorial

GDB Tutorial. A Walkthrough with Examples. CMSC 212 - Spring 2009. Last modified March 22, 2009. GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

More information

Programming Languages

Programming Languages Programming Languages Programming languages bridge the gap between people and machines; for that matter, they also bridge the gap among people who would like to share algorithms in a way that immediately

More information

16.1 DataFlavor. 16.1.1 DataFlavor Methods. Variables

16.1 DataFlavor. 16.1.1 DataFlavor Methods. Variables In this chapter: DataFlavor Transferable Interface ClipboardOwner Interface Clipboard StringSelection UnsupportedFlavorException Reading and Writing the Clipboard 16 Data Transfer One feature that was

More information

Advanced compiler construction. General course information. Teacher & assistant. Course goals. Evaluation. Grading scheme. Michel Schinz 2007 03 16

Advanced compiler construction. General course information. Teacher & assistant. Course goals. Evaluation. Grading scheme. Michel Schinz 2007 03 16 Advanced compiler construction Michel Schinz 2007 03 16 General course information Teacher & assistant Course goals Teacher: Michel Schinz Michel.Schinz@epfl.ch Assistant: Iulian Dragos INR 321, 368 64

More information

Brent A. Perdue. July 15, 2009

Brent A. Perdue. July 15, 2009 Title Page Object-Oriented Programming, Writing Classes, and Creating Libraries and Applications Brent A. Perdue ROOT @ TUNL July 15, 2009 B. A. Perdue (TUNL) OOP, Classes, Libraries, Applications July

More information

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 This Week CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 School of Computer Science University of St Andrews Graham Kirby Alan Dearle More on Java classes Constructors Modifiers cdn.videogum.com/img/thumbnails/photos/commenter.jpg

More information

Software Engineering Techniques

Software Engineering Techniques Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

More information

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages ICOM 4036 Programming Languages Preliminaries Dr. Amirhossein Chinaei Dept. of Electrical & Computer Engineering UPRM Spring 2010 Language Evaluation Criteria Readability: the ease with which programs

More information

Technical Writing - Definition of Bad and Good Code

Technical Writing - Definition of Bad and Good Code 1 Workshop on Distributed Software Management for e-science Day 2 - Software Design Lecture 4 Code Design Basics Geoff Cawood Consultant, EPCC Telephone: +44 131 650 5120 Email: geoffc@epcc.ed.ac.uk 4Low

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 2, 2015 1 3 A First MaSH Program In this section we will describe a very

More information

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture Last Class: OS and Computer Architecture System bus Network card CPU, memory, I/O devices, network card, system bus Lecture 3, page 1 Last Class: OS and Computer Architecture OS Service Protection Interrupts

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Programming in Access VBA

Programming in Access VBA PART I Programming in Access VBA In this part, you will learn all about how Visual Basic for Applications (VBA) works for Access 2010. A number of new VBA features have been incorporated into the 2010

More information

C Compiler Targeting the Java Virtual Machine

C Compiler Targeting the Java Virtual Machine C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One of the

More information

C# and Other Languages

C# and Other Languages C# and Other Languages Rob Miles Department of Computer Science Why do we have lots of Programming Languages? Different developer audiences Different application areas/target platforms Graphics, AI, List

More information

1 The Java Virtual Machine

1 The Java Virtual Machine 1 The Java Virtual Machine About the Spec Format This document describes the Java virtual machine and the instruction set. In this introduction, each component of the machine is briefly described. This

More information

Code Refactoring and Defects

Code Refactoring and Defects Code Refactoring and Defects Reusing this material This work is licensed under a Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International License. http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en_us

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third

More information