Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comp1004: Conclusions Revision Session. Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some.

Similar presentations


Presentation on theme: "Comp1004: Conclusions Revision Session. Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some."— Presentation transcript:

1 Comp1004: Conclusions Revision Session

2 Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some Last Words

3 Recap: The Basics

4 Classes and Objects http://www.animalblueprintcompany.com/ 1 Class 101 Objects

5 The JVM So the JVM is software that allows your Java program to run on any platform where there is a JVM The JVM? Your Program The Machine

6 Dog.java Structure public class Dog { public String noise = “Woof”; public void bark() { System.out.println(noise); } Source file Class Member Variable Method Statement

7 The main method Creates the objects you need and tells them what to do, a bit like a conductor in an orchestra It doesn’t matter which class you put the main method in. You can put it in its own one if you like – But there must be 1 and only 1 in the whole program (program is a set of classes that work together) Dog.java public class Dog { public String noise = “Woof”; public void bark() { System.out.println(noise); } public static void main(String[] args){ Dog d = new Dog(); d.bark(); }

8 if/else public class Account{ int balance;//the bank balance boolean active;// true if the account is active active = true;//set active to true //some code omitted public void withdrawFiver{ if(!active){ System.out.println(“Your account isn’t active”); System.out.println(“No withdrawal allowed”); }else { balance = balance - 5; }

9 PrimitivesObjects Defined?defined in Javadefined in Classes Stored?stored directly in variablesa reference is stored in the variable Passed?Pass by copyPass by reference b Elephant a int int a; a = 10; Elephant b; b = new Elephant(); Primitives vs. References

10 Methods and Parameters public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); } public void withdraw(int amount){ balance = balance - amount; } Values received by a method are called parameters. Within the method they can be used like any other local variable Values passed into a method are called arguments

11 Overloading public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); } public void withdraw(int amount){ balance = balance - amount; } public void withdraw(int amount, String desc){ balance = balance - amount; System.out.print(“Withdrew £”); System.out.print(amount); System.out.print(“ via ”); System.out.println(desc); } Several Methods can have the same name as long as their signatures (types and order of parameters) are different. Methods can take multiple parameters

12 Loops for (int i = 0; i < 10; i++) { System.out.println(i); } int i = 0; while(i < 10){ System.out.println(i); i++; } initialization; condition; statechange Condition is checked at start. Loops zero or more times. int i = 0; do { System.out.println(i); i++; } while (i < 10); Condition is checked at end. Loops one or more times. A convenience loop for when we know it advance how many times we want to iterate. Loops zero or more times.

13 Arrays int[] numStore; numStore = new int[9]; numStore[0] = 77; System.out.println(numStore[0]); [ ] 1 0 2345 6 7 8 77 numStore int[] Declaration Instantiation Assignment Retrieval

14 Iterating Over an Array int numStore = new int[9]; //some missing code to fill the array with values for(int i = 0; i < 9; i++){ System.out.print(“Number at position ” + i); System.out.println(“ is ” + numStore[i]); } Iterating over an array is so common that Java now includes a loop specifically to do it. int numStore = new int[9]; //some missing code to fill the array with values for(int n : numStore){ System.out.println(“Number is ” + n); } Like the for loop the ‘for each’ loop is a shortcut, that is a bit neater than writing the code the long way. But it can only be used for access (e.g. n++ would not increment the value in the array) And it hides the current index

15 ArrayLists ArrayList kennel = new ArrayList(); kennel.add(new Dog(“Rover”)); kennel.add(new Dog(“Fido”)); kennel.add(new Dog(“Patch”)); kennel.add(new Cat(“Mr Tiddles”)); for(int i = 0; i < kennel.size(); i++) { kennel.get(i).bark(); } ArrayLists store objects of any type Which means we can mix up the types of objects in the ArrayList Which may cause problems later if we make assumptions about what is in there! In fact this code will not compile, because Java does not know what is in the ArrayList, and therefore will not let you call bark on it

16 Generics ArrayList kennel = new ArrayList (); kennel.add(new Dog(“Rover”)); kennel.add(new Dog(“Fido”)); kennel.add(new Dog(“Patch”)); kennel.add(new Cat(“Mr Tiddles”)); for(int i = 0; i < kennel.size(); i++) { kennel.get(i).bark(); } It would be better if we could ensure that the ArrayList only contained Dogs in the first place This is easily done because ArrayList uses a mechanism called generics. We can specify the type allowed when we create the ArrayList. Now Java will only allow us to add things of type Dog. So this line will force a compile time error

17 Recap: The Pillars

18 The Three Pillars of OOP EncapsulationInheritancePolymorphism

19 Encapsulation Take this example class where age is modelled as an int public class Student { int age = 20; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } public int getAge(){ return age; }

20 Encapsulation public class Student { //int age = 20; Calendar dateOfBirth; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } //public int getAge(){ //return age; //} public int getAge(){ Calendar rightNow = Calendar.getInstance(); int a = calculateAge(rightNow, dateofBirth); return a; } Take this example class where age is modelled as an int We might change the way that age is implemented – e.g. to make it based on the current date. Because we used an Accessor we do not need to alter main

21 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Inheritance The sub-classes inherit all the properties and methods from the superclass Any class that is inherited from is called a superclass Any class that inherits from another is called a subclass They can also add more of their own

22 Inheritance in Java public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; // constructors and methods omitted. } You don’t need to add anything to the superclass

23 Inheritance in Java You don’t need to add anything to the superclass public class CD extends Item { private String artist; private int numberOfTracks; // constructors and methods omitted. } public class DVD extends Item { private String director; // constructors and methods omitted. } You declare the inheritance in the sub-class using the extends keyword

24 Encapsulation Expanded In fact Java uses several keywords for encapsulation Public – Everyone can see it Protected – Only this class, its sub-classes and the package can see it Default (no keyword) – Only this class and the package can see it Private – Only this class can see it

25 Encapsulation Expanded Rule-of-thumb: assume everything should be protected Explicitly make public the methods (and sometimes properties) that you want other classes to use Explicitly make private any implementation details that you want to hide even from sub-classes In fact Java uses several keywords for encapsulation Public – Everyone can see it Protected – Only this class, its sub-classes and the package can see it Default (no keyword) – Only this class and the package can see it Private – Only this class can see it

26 Polymorphism: Dynamic Binding ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); Remember that we can use a subclass whenever a reference or collection is expecting the superclass – this is called substitution

27 Polymorphism: Dynamic Binding ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Remember that we can use a subclass whenever a reference or collection is expecting the superclass – this is called substitution Because of dynamic binding these will call the most specific version of the method, even though we iterating through an Animal collection

28 Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

29 Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

30 Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

31 Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

32 Polymorphism Substitution, Overriding and Dynamic Binding gives us Polymorphism – (greek for many shapes) Polymorphism means that we can create methods that deal with superclasses and then: – We can pass them instances of sub-classes (substitution) – And when it calls methods on those sub-classes if there are more specific methods defined (via overriding) the call gets diverted at run-time to the most specific method (dynamic binding)

33 The Three Pillars of OOP EncapsulationInheritancePolymorphism

34 Recap: The Extras

35 Abstract Classes An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: abstract void sendMsg(String msg); If a class includes abstract methods, the class itself must be declared abstract, as in: public abstract class Broker { // declare fields // declare non-abstract methods abstract void sendMsg(String msg); } When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

36 Multiple inheritance In Java, multiple inheritance is not allowed This is because it gets hard to resolve clashes Class A Class B foo() Class B foo() Class C foo() Class C foo() Class D If foo() is called on an object of type D, which method gets called?

37 Interfaces Java provides Interfaces to allow you to solve this problem without introducing any of the awkward questions about clashing methods An Interface behaves like a 100% abstract class – i.e. containing only abstract methods A Class can only extend one other Class, but it can implement many Interfaces An Interface is like a contract, any class that implements that Interface guarantees to provide code for its methods

38 Exceptions Code that takes risks can throw Exceptions to show that something has gone wrong We can then catch that Exception and tidy up the mess try { //some code that might throw ExceptionName throw new ExceptionName(“Oops – cannot open file”); } catch (ExceptionName e) { //code to run in case an ExceptionName is thrown }

39 Exceptions Rather than catching an Exception you can pass it on down the call stack This allows the Exception to be handled at the best possible place But remember it must be caught somewhere!

40 Static Static fields – A property belongs to the class, and is shared between all instances – Can be combined with final to create global constants static final int NO_OF_CARDS = 52; Static methods – invoked on the class rather than an instance – can not depend on the values of fields stored in an instance (or use the this keyword) public static void main(String[] args) { //some code }

41 Patterns Common ways to solve typical programming problems, examples include: – Iterators – Decorators – Observers – Factories – Singletons – Strategies Useful to learn the most common ones, they will be useful many times in your programming life!

42 Feedback and Course Evaluation

43 Course Evaluation Please answer the evaluation forms I have passed around These really matter – we really do take notice of them And alter the modules as a result! They are anonymous, so please be honest but constructive

44 Exam

45 The Good News Three hour exam – so lots of time – held in one of the University lab rooms – done on a PC using the tools you are used to Open Book – you can take in textbooks and notes – you can access the web (e.g. look at help pages and/or the Java API)

46 The Bad News But it is still an Exam – No communication allowed (e.g. IM, Facebook, file sharing) – No pre-prepared solutions allowed – No de-compilers allowed Invigilators will be present to enforce the rules and make sure the machines and software are working properly – They cannot answer questions about your code!

47 The Questions There are three questions, you must try and answer all of them Question 1 (20%) – Is the easiest question – Explores your ability to read code and understand programming terms Question 2 (50%) – Is the main question – Explores your ability to write code and solve programming problems Question 3 (30%) – Is the advanced question – Explores your ability to understand a program design, write more advanced code and think creatively

48 Some advice Most people will not finish the whole exam – Do not worry – Stay calm – Start at the beginning – Complete as much as you can Be defensive – Read each question thoroughly before you start it – Save often – Submit your solutions as you go (via handin machine) Check out the past exam papers: – https://secure.ecs.soton.ac.uk/module/COMP1004/pastpapers

49 Some Last Words

50 A Dirty Secret No matter how we teach you will mainly learn through practice! Programming is the single most important skill for a computer scientist or software engineer – Systematic thinking and problem solving – Abstraction and data modeling Did we mention that you need to practice?

51 PRACTICE! “I've often thought that sucking less every year is how humble programmers improve. You should be unhappy with code you wrote a year ago.” - Jeff Atwood, http://www.codinghorror.com/ “I have no talent. What I do have is a lot of practice. And I am not talking about occasionally dabbling in Ruby on the weekends. I am talking about the kind of practice where I beat code that isn’t working into submission (though often times the code wins).” - John Nunemaker, http://railstips.org/

52 Best of Luck and Have Fun!


Download ppt "Comp1004: Conclusions Revision Session. Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some."

Similar presentations


Ads by Google