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

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Advertisements

ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Abstract Classes and Interfaces
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Comp1004: Introduction I Welcome!. Welcome to Programming Principles Dr. David Millard Dr. Julian Rathke Dr.
Programming Languages and Paradigms Object-Oriented Programming.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Programming in Java CSCI-2220 Object Oriented Programming.
Review Class Inheritance, Abstract, Interfaces, Polymorphism, GUI (MVC)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Comp1004: Programming in Java I Variables - Primitives, Objects and Scope.
OOP Basics Classes & Methods (c) IDMS/SQL News
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Coming up Which methods are where? – Overriding Calling super’s methods Coupling and cohesion.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Comp1004: Introduction III Java. Content How Java Works: The JVM Writing a Class in Java – Class – Member Variables – Method – Statement Magic incantations.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Comp1202: Conclusions Revision Session. Coming up Key Concepts - The Pillars HashMaps Exceptions The Exam Some Last Words.
Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.
Comp1004: Loops and Arrays I Whiles, For and Arrays[]
Coming up Inheritance – Code duplication – Super classes – Constructors Polymorphic collections – “Anywhere a super class is, a sub class can go” Casting.
Content Programming Overview The JVM A brief look at Structure – Class – Method – Statement Magic incantations – main() – output Coding a Dog Programming.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Content Programming Overview The JVM A brief look at Structure
Comp1004: Loops and Arrays II
Inheritance and Polymorphism
Comp1202: Conclusions Revision Session.
Java Programming Language
Comp1202: Introduction III
Encapsulation and Constructors
Java Inheritance.
Java Programming Language
Comp1202: Inheritance I Super and Sub-classes.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Comp1004: Conclusions Revision Session

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

Recap: The Basics

Classes and Objects 1 Class 101 Objects

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

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

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

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

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

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

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

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.

Arrays int[] numStore; numStore = new int[9]; numStore[0] = 77; System.out.println(numStore[0]); [ ] numStore int[] Declaration Instantiation Assignment Retrieval

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

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

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

Recap: The Pillars

The Three Pillars of OOP EncapsulationInheritancePolymorphism

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

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

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

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

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

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

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

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

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

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

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

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

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

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)

The Three Pillars of OOP EncapsulationInheritancePolymorphism

Recap: The Extras

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.

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?

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

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 }

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!

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 }

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!

Feedback and Course Evaluation

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

Exam

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)

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!

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

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

Some Last Words

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?

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

Best of Luck and Have Fun!