Presentation is loading. Please wait.

Presentation is loading. Please wait.

CECS 220: OOP design with java

Similar presentations


Presentation on theme: "CECS 220: OOP design with java"— Presentation transcript:

1 CECS 220: OOP design with java
Final Exam Review Session by REACH

2 Outline Arrays Inheritance Polymorphism Exceptions Recursion

3 To get this presentation:
TestReviews.html

4 Arrays Arrays are simple but powerful programming language constructs used to group and organize data It is simply a list of values and an index is the number corresponding to each position in an array An array of size N is indexed from 0 to N-1 To declare an array: datatype[] arrayName = new datatype[size]; E.g. int[] height = new int[10]; To access an array element: arrayName[indexNumber]; E.g height[3]; In java, an array is an object that MUST be instantiated A for statement can be used to traverse an array easily

5 Arrays: Bounds Checking
This is used to ensure that an index used to refer to an element in in range One way of achieving this is by using the length constant which returns the length of the array

6 Arrays: an Example int[] height = new int[5]; for(int i = 0; i < height.length; i++) { height[i] = i + 1; System.out.println("height["+i+"]" + "=" + height[i]); } RESULT height[0]=1 height[1]=2 height[2]=3 height[3]=4 height[4]=5

7 Initializer List This can be used to instantiate an array object instead of using the new operator Int[] scores = {10, 19, 5, 6, 8, 20}; This can only be used when an array is first declared N.B: a for statement can be used to access each member of the array. This can be used if an operator must occur on every member of the array E.g. For(score: scores){ if(score > 18){ system.out.println(“You’ve qualified for a prize”); }

8 Arrays as Parameters An entire array can be passed as a parameter to a method An element of an array can also be passed as a parameter to a method The for statement can also be used to loop through the array int[] primeNums = {2,3,5,7,11,13,17,19}; for(int prime: primeNums){ system.out.print(prime + ” ”); } Result:

9 Arrays of Objects Objects can also be stored in and accessed from an array like primitive data types Instantiating an array of objects reserves room to store references only The objects that are stored in each element must be instantiated separately An example of this is storing an array of strings as follows: String[] names = {“Alice”, “Jonah”, “Lola”, “Paul”}; Another example shows initializing an array of Grade objects Grade[] grades = {new Grade(“A”, 95), new Grade(“A”, 99), new Grade(“F”, 39), new Grade(“B”, 82)};

10 2 - dimensional Arrays A 2-d array can be used to store a table of values Int[][] table = new int[5][10]; In the example given above, the table will have 5 rows and 10 columns The table can be dynamically accessed using a nested for-each statement To access a specific cell/value: table[x][y]; It is rare to use a table with more than 2 dimensions in OOP

11 Question Describe five programs that would be difficult to implement without using arrays

12 Inheritance One of the key ‘pillars’ of Object Oriented Programming in which a class can inherit the fields and methods of another class. Also called an ‘is-a’ relationship. It is the process of deriving a new class from an existing one One purpose of inheritance is to reuse existing software Terms: Super Class: Also known as the parent or base class. This class has its features inherited by another class. Sub Class: Also known as the extended or child class. This class inherits its features from the super class, often along with adding its own features Usage: General Format: class SubClass extends SuperClass Example: class Dog extends Animal Multiple different and unique sub classes can extend from one super class. For example, a class Cat could also extend Animal. Sub classes can be derived from other sub classes. For example, a class Bulldog could extend Dog. You can NOT extend more than one class (no hybrid inheritance)

13 Inheritance Example public class Animal{ public int weight; public Animal(int weight){ this.weight = weight; } public void setWeight(int weight){ public int getWeight(){ return this.weight; public String toString(){ return "Weight: " + this.weight + " lbs"; public class Dog extends Animal{ public String breed; public Dog(int weight, String breed){ super(weight); this.breed = breed; public void setBreed(String breed){ public String getBreed(){ return this.breed; return super.toString() + "\tBreed: " + this.breed;

14 Inheritance Cont’d The ‘Protected’ modifier makes it possible to access methods and properties in superclass from its subclasses only Protected visibility provides the best possible encapsulation that permit inheritance A child class can override (redefine) the parent’s definition of an inherited method The ‘final’ modifier can be used if we don’t want the method to be modified in the sub class When using inheritance, common features should be located as high in a class hierarchy as is reasonably possible

15 Inheritance: Abstract Classes and Interfaces
An abstract class cannot be instantiated. It represents a concept on which other classes can build their definition. They serve as placeholders in a class hierarchy They represent abstract concepts that are insufficiently defined to be useful by itself A class derived from an abstract parent must override all of it’s parent’s abstract methods or the derived class will also be considered abstract Inheritance can be applied to interfaces so that one interface can be derived from another The final modifier can be used to restrict inheritance

16 Polymorphism Allows an object to have multiple forms, occurs most often when a parent class refers to a child class. The reference variable from the parent class once declared cannot be changed, but it can be assigned and reassigned to any valid objects, usually entailing itself or any of its child classes. Polymorphism allows us to apply a consistent approach to inconsistent behaviors Usage: Assume classes on previous slide. Animal animal = new Animal(15); animal.toString() calls the toString() method within the Animal class Animal animal = new Dog(10, “Poodle”); animal.toString() calls the toString() method within the Dog class

17 Overriding Methods A child class can override (redefine) the parent’s definition of an inherited method When overriding methods: Argument list should be exactly like the overridden method It must return the same datatype as the overridden method Access level cannot be more restrictive then the overridden method’s access level Instance methods can only be overridden if they are inherited by the subclass A method declared final cannot be overridden Constructors cannot be overridden but they can be OVERLOADED

18 Polymorphism via Interfaces
An Interface describes a set of methods Class variables can be declared using the static keyword Constructors and instance variables are not permitted Using an interface can be viewed as a contract signed by a class to provide implementations for ALL methods described by the interface Public interface Database{ public void connect(); public void disconnect(); public int getNumberOfRows(); } A class can implement multiple interfaces Interfaces are used using the implements keyword

19 Polymorphism via interfaces
The use of interfaces is also another way to ensure polymorphism A class can implement more methods than those specified in the interface

20 Example of Method overriding
NOTE: when invoking the superclass version of an overridden method, super keyword is used

21 Object Class In java, all classes are derived directly or indirectly from the object class The toString() and equals() methods are inherited by every java program The default equals() method in java determines whether 2 objects are equal i.e if they refer to the same object (aliases) This method is mostly overridden in favor of a more appropriate definition of equality for the class Another method of the object class is the clone() method which creates and returns a copy of the object

22 Exceptions Errors and exceptions are objects that represent unusual or invalid processing Each catch clause handles a particular kind of exception that may be thrown within the try block The finally-clause is executed whether the try block is exited normally or because of a thrown exception

23 Exception Propagation
If an exception is not caught and handled when it occurs it is propagated to the calling method This propagation continues until the exception is caught and handled or until it is passed out of the main method which terminates the program and produces an exception message A programmer must carefully consider how and where exceptions should be handled, if at all

24 Recursion A programming technique in which a method calls itself. Often times recursion is more efficient than loops and can be used to solve a wide variety of problems. Recursive functions are made up of bases cases (non-recursive) and general cases (recursive). Mathematical problems and formulas are often expressed recursively Recursive calls operate like a stack, with the last recursive call being executed first and the first recursive call being executed last. Ex. Use recursion to write a method that returns the factorial of a number. Show the base case and the general case. public static int factorial(int n){ if (n == 1){ return 1; //Base Case (non-recursive) }else{ return n * factorial(n – 1); //General Case (recursive) }

25 Collections A collection is an object that serves as a repository for other objects An object with a well-defined interface, is a perfect mechanism for implementing a collection Some collections maintain an order while others do not. Some are heterogeneous while others are homogeneous Examples of collections are arrays, arraylist, queues, stacks etc The size of a dynamic data structure grows and shrinks as needed

26 Collections

27 QUESTIONS?


Download ppt "CECS 220: OOP design with java"

Similar presentations


Ads by Google