Remember this: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; // of type Animal an_arr[1] = a_dog ; //of type Dog an_arr[2] = a_wolf; // of type Wolf.

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
CS 106 Introduction to Computer Science I 04 / 30 / 2007 Last lecture :( Instructor: Michael Eckmann.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
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,
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Chapter 19 Java Data Structures
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
CS 106 Introduction to Computer Science I 04 / 25 / 2007 Instructor: Michael Eckmann.
The Java Collections Framework (JCF) Introduction and review 1.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
ArrayList, Multidimensional Arrays
Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions. Avoiding duplication and redundancy.
Inheritance (Part 4) Abstract Classes 1.  sometimes you will find that you want the API for a base class to have a method that the base class cannot.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Chapter 18 Java Collections Framework
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
10-Nov-15 Java Object Oriented Programming What is it?
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.,
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
CSE 1201 Object Oriented Programming ArrayList 1.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
CH10 Supplementary Material Prepared by Fatimah Alakeel Oct 2010.
OOP Basics Classes & Methods (c) IDMS/SQL News
Collections Dwight Deugo Nesa Matic
Object Oriented Programming in Java Habib Rostami Lecture 7.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Lecture 5:Interfaces and Abstract Classes
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Sixth Lecture ArrayList Abstract Class and Interface
Java Programming Language
Collections Framework
JCF Collection classes and interfaces
Chapter 14 Abstract Classes and Interfaces
TCSS 143, Autumn 2004 Lecture Notes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Remember this: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; // of type Animal an_arr[1] = a_dog ; //of type Dog an_arr[2] = a_wolf; // of type Wolf for (int i = 0; i < 3; i++) { an_arr[i].talk(); if (an_arr[i].isaPet) { System.out.println(an_arr[i].name); } } Here we could use the loop because each derived class had the talk method and the name field The subclasses had talk methods that overrode the parent class, but we could not do this loop unless all objects in the array had a talk method. What if we want to ensure that every subclass has their own version of a method? We want to force each subclass to have its own talk method?

Abstract Methods  Suppose you have many class behaviors that have a common first step and a common last step  The middle step is different  Wouldn’t it be nice if you could write this code once: public void commonBehavior() { //... code that does first step doMiddleStep(); //... code that does last step }

You can! public void commonBehavior() { //... code that does first step doMiddleStep(); //... code that does last step } public abstract void doMiddleStep();

Abstract Classes  Declared using the abstract keyword  abstract class  Cannot be instantiated (can’t make an object from this class)  Must be a superclass to other classes  fields, methods and constructors are accessed in the same way as with the other subclasses.  abstract methods  methods without any implementation  must be overridden by a subclass // forces you to write a definition of the method in the subclass  A class must be abstract if it has abstract methods

What is output? abstract class Animal { public boolean isaPet; public String name; public Animal() { this(true,"Fred"); } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; } public String getName() { return name; } public abstract void talk(); public void talking() { System.out.print(“The animal says "); talk(); System.out.println(“ and then it is quiet.”) } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void talk() { System.out.println("bark bark"); } public class Main{ public static void main(String[] args) { Dog a_dog = new Dog("Spot"); a_dog.talking(); } } … The animal says: bark bark and then it is quiet

Another Example: Graphing:  Circles  Rectangles  Lines,  many other graphic objects.  all have certain states  position,  orientation,  line color,  fill color  All have certain behaviors  moveTo,  rotate,  resize,  Draw  Some of these states and behaviors are the same for all graphic objects  (for example: position, fill color, and moveTo).  Others require different implementations  (for example, resize or draw).  All Graphic Objects must be able to draw and resize  They just differ in how they do it.

abstract class GraphicObject { protected int x, y; protected String color; … public void moveTo(int newX, int newY) { penup() goto(x,y); } public abstract void draw(); public abstract void resize(int x); } class Circle extends GraphicObject { int radius; … public void draw() { pendown(); drawCircle(radius); } public void resize(int x) { eraseCircle(radius); radius = radius + radius * ((double)x/100); drawCircle(radius); } class Rectangle extends GraphicObject { int length; int width; … public void draw() { pendown() forward(length); rotate(90); forward(width); rotate(90); forward(length); rotate(90); forward(width); rotate(90); } public void resize(int x) { length = length * ((double)x/100); width = width * ((double)x/100);... }

Interfaces  contains only constants and abstract methods  Unlike abstract classes they cannot have fields (properties) or implemented methods (methods with code in them)

10 Define an Interface To distinguish an interface from a class, Java uses the following syntax to define an interface: 10 public interface InterfaceName { constant declarations; //constants!! Things you give a value to and never touch again other //than to use the value method signatures; } Example : public interface Edible { /** Describe how to eat */ public abstract String howToEat(); public abstract String howToDrink(); public abstract Boolean isEdible(Food fooditem); }

Why Interfaces?  Remember, all subclasses of an interface must implement (make code for) each method in the interface

Laziness  All fields in an interface MUST BE public static (e.g., constants)  All methods MUST BE public abstract For this reason, these modifiers can be omitted, as shown below: A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME e.g., T1.K

public interface AnimalInterface { abstract public String talks(); abstract public String eats(); abstract public String moves(); } class Cat implements AnimalInterface { public Cat() { } public String talks(){ return("meow meow"); } public String eats(){ return("Eats mice"); } public String moves(){ return("prowls"); } public class Bunny implements AnimalInterface{ public Bunny() { } public String talks(){ return("no idea"); } public String eats(){ return("Eats hay"); } public String moves(){ return("hops"); } public class Cow implements AnimalInterface{ public Cow() { } public String talks(){ return("moo moo"); } public String eats(){ return("Eats grass"); } public String moves(){ return("rarely runs"); } public static void main(String[] args) { AnimalInterface[] arr = new AnimalInterface[3]; arr[0] = new Cow(); arr[1] = new Cat(); arr[2] = new Bunny(); for (AnimalInterface x: arr) { System.out.println(x.talks()); System.out.println(x.moves()); System.out.println(x.eats()); }

Using interfaces  Interfaces are not part of the class hierarchy  A class may implement many different interfaces  Polymorphism still holds  An instance of class X that implements interface Y can be used as the base interface type: Y myY = new X();

public interface AnimalInterface { abstract public String talks(); abstract public String eats(); abstract public String moves(); } public interface FarmThings { abstract public boolean isaFarmTool(); abstract public String produces(); } public class Cow implements AnimalInterface, FarmThings{ public Cow() { } public String talks(){ return("moo moo"); } public String eats(){ return("Eats grass"); } public String moves(){ return("rarely runs"); } public boolean isaFarmTool(){ return false; } public String produces(){ return "milk"; }

Abstract vs Interface  Use Abstract if:  There’s sharable code that all subclasses will instantiate the same  There’s sharable fields that all subclasses will want to have  There are some methods or fields that you want to keep protected from outside code (or private, for that matter)  Use Interfaces if:  Classes that may not be terribly related will still use the same methods  You want to be able to use methods (by knowing their input parameters and output type), but you’re not terribly concerned with how the method is implemented

Collections (Data Structures)

Collection object: data Structure An object that groups things. We group things so we can store, retrieve, and manipulate data. Collections : Automatically grow in size Contain objects Have a bunch of convenient methods written for us E.g., add Sometimes referred to as Containers (interchangeably)

Collections: Collections are an abstract class So we never make a collection object We have a bunch of methods that belong to all subclasses derived from the collection class. Can override the methods depending on the type of collection

Collections: Many different types Lists: ArrayList LinkedList Sets No duplicates No order (TreeSets happen to have an order) Maps Mapping a key to a value E.g., our soccer players: map each player to a position Each player is unique, each position doesn’t have to be The player’s name should bring up their position

ArrayLists: One example of a Collection: used to store a list of some objects Remember arrays? Student[] classroom = new Student[60]; Why is this a pain? Do you see any difficulties with this array? How do you add a 61 st student? What if students drop?

ArrayLists: The ArrayList class has the following methods: add(o) appends the new object o to the end of the list add(i, o) adds the object o at the index i (an int) addAll( c) adds everythin from collection c to the ArrayList (at the end) clear() removes all elements from the list contains(o) returns true if the list contains the object o get(i) returns the element located at index i in the list indexOf(o) returns the index of the object o in the list isEmpty() returns true if the list contains no elements lastIndexOf(o) returns the index of the last matching element in the list remove(index) removes the element at index and returns it from the list remove(object) removes the object from the list and returns true if successful, false otherwise removeAll(c) remove from this list all the elements in the collection list removeRange(fromindex, toindex) removes everything in the list from the fromindex to the toindex (excluding the toindex) retainAll(c) keeps in the list only objects in the collection set(index, o) sets the element at the index to the object o size() returns the number of elements in the list subList(fromindex, toindex) returns a list from the from index to the toindex.

ArrayLists: import java.util.ArrayList; ArrayList al = new ArrayList(); // this works… What type is al? This is a collection: what is it a collection of?

ArrayLists We don’t have to specify the type for the methods in ArrayList to work We can still use the methods associated with the ArrayList But we can… And then we can use the methods and values associated with the class type: ArrayList al = new ArrayList (); Or the shortcut: ArrayList aI= new ArrayList();

Example: public static void main(String[] args) { ArrayList DogShowWinners = new ArrayList(); DogShowWinners.add(new Dog("Spot")); DogShowWinners.add(new Dog("Fang")); DogShowWinners.add(new Dog("Puppy")); DogShowWinners.add(new Dog("Bernice")); DogShowWinners.add(new Dog("Sandy")); System.out.println("List size? "+DogShowWinners.size()); DogShowWinners.add(2,new Dog("Prince")); for (Dog x: DogShowWinners) { System.out.println(x.getName()); } List size? 5 Spot Fang Prince Puppy Bernice Sandy

Using dog methods? System.out.println(DogShowWinners.get(3).getName()); public static void main(String[] args) { ArrayList DogShowWinners = new ArrayList(); DogShowWinners.add(new Dog("Spot")); DogShowWinners.add(new Dog("Fang")); DogShowWinners.add(new Dog("Puppy")); DogShowWinners.add(new Dog("Bernice")); DogShowWinners.add(new Dog("Sandy")); System.out.println("List size? "+DogShowWinners.size()); DogShowWinners.add(2,new Dog("Prince")); }

Diff between arrays and ArrayLists OperationArrayArrayList Creating Accessing Updating Getting Size Adding a new element Inserting a new element Removing an element Removing all elements String[] a = new String[10] a[index] a[index] = “London”; a.length ArrayList list = new ArrayList(); list.get(index); list.set(index,”London”); list.size(); list.add(“London”); list.add(index,”London”); list.remove(index); list.clear();

ArrayLists: Can’t do: ArrayList x = new ArrayList(); (Can’t use primitive types, must use object types) Instead: ArrayList x = new ArrayList(); ArrayList These are object versions of primitive types

Behind the scenes: We create a relatively long array that can resize dynamically This means that if we add an object, we move everything from where we added it down by one If we’re adding to the end, how many operations do we need to do? If we add to the beginning of the list? Removing an object – how many operations will we need to remove the object from the array?

ArrayLists: What are ArrayLists good at? Adding another item to the end of the list Except when have to double size Removing from the end of the list Except when have to halve the size Finding what is at a particular index Where are they inefficient? Adding another itme When adding to the beginning of the list When you have to double the length of the list Removing When you have to halve the length of the list When you remove from the beginning of the list Joining two lists Inserting a new list into the middle of the list Finding if a particular object is in the list

Collections: Many different types Lists: ArrayList LinkedList Sets No duplicates No order (TreeSets happen to have an order) Maps Mapping a key to a value E.g., our soccer players: map each player to a position Each player is unique, each position doesn’t have to be The player’s name should bring up their position

Linked Lists Another type of list in our collections

Linked List methods: The LinkedList class has the following methods (and more): add(o) appends the new object o to the end of the list add(i, o) adds the object o at the index i (an int) addAll(c) adds all of the elements in c to the end of the linked list clear() removes all elements from the list contains(o) returns true if the list contains the object o get(i) returns the element located at index i in the list indexOf(o) returns the index of the object o in the list isEmpty() returns true if the list contains no elements lastIndexOf(o) returns the index of the last matching element in the list remove(index) removes the element at index and returns it from the list remove(object) removes the object from the list and returns true if successful, false otherwise removeAll(c) remove from this list all the elements in the collection list retainAll(c) keeps in the list only objects in the collection set(index, o) sets the element at the index to the object o size() returns the number of elements in the list

Linked Lists Both Implement the list interface What does that mean? Does pretty much what ArrayLists do: Just does it differently Trying to find ways of being efficient

Why so many methods in common with ArrayLists? Both ArrayLists and LinkedLists implement the List Interface, which extends the collection interface List Interface: add(x) addAll(c) clear() contains(x) containsAll(c) equals(x) hashCode() isEmpty() remove(x) removeAll(c) retainAll(c) Size() toArray()

Back to Linked Lists LinkedList x = new LinkedList(); x.add(“cat”); x.add(“dog”); x.add(“bunny”); x.remove(“dog”); ArrayList q = new ArrayList(); q.add(“cat”); q.add(“puppy”); q.add(“bunny”); q.add(“cow”); if (q.containsAll(x) ) { System.out.println(“all the animals are in the list”); }

So why do we have LinkedLists and ArrayLists? Because of how they work…

Linked Lists (behind the scenes): Linked Lists are a series of single objects, with each object having a pointer, or address (aka a link) to the next object. Each element (node) consists of 2 things: data and a pointer to another node. The first node is the head, and the last is the tail (pointing to null) This is a representation of a singly linked list (meaning each node points to the next node in the list).

Singly Linked List class: Behind the scenes: public class Node { public AnyType data; public Node next; public Node(AnyType data, Node next) { this.data = data; this.next = next; } public Node(AnyType data) { this.data = data; this.next = Null; }

Node n1 = new Node(3); Node n2 = new Node(4,n1); Node n3 = new Node(7,n2); Node t = n3; int k = 0; while (t != null) { System.out.println(t.data); k = k + t.data; t = t.next; } System.out.println(k); public class Node { public AnyType data; public Node next; public Node(AnyType data, Node next) { this.data = data; this.next = next; } public Node(AnyType data) { this.data = data; this.next = Null; } Behind the scenes…

What you’d write: LinkedList x = new LinkedList(); x.add(7); x.add(4); x.add(3); Iterator itr = x.iterator(); k = 0; while(itr.hasNext()) { int y = itr.next(); System.out.println(y); k+= y; } System.out.println(k); Node n1 = new Node(3); Node n2 = new Node(4,n1); Node n3 = new Node(7,n2); Node t = n3; int k = 0; while (t != null) { System.out.println(t.data); k = k + t.data; t = t.next; } System.out.println(k);

Why Lists? public void f(List l ) { l.add(3); l.add(7); l.add(4); Iterator itr = l.iterator(); int k = 0; while(itr.hasNext()) { int y = itr.next(); System.out.println(y); k+= y; } System.out.println(k); } public static void main(String[] args) { LinkedList x = new LinkedList(); ArrayList y = new ArrayList(); f(x); f(y); }

Why linked lists? Better at: Inserting into the list Sort of – need to know where to insert Or need to insert at end or beginning Do we ever have to double or halve? Removing from the list Again, sort of... Really good at joining lists! Bad at: Finding what is at a particular index Finding if something is in the list

Technical Analysis: LinkedLists vs ArrayLists For ArrayList get(int index) is O(1) //main benefit of ArrayList add(E element) is O(n) worst-case (since the array must be resized and copied) add(int index, E element) is O(n) worst-case (as above) remove(int index) is O(n - index) (i.e. removing last is O(1)) Concatenating (addAll) – O(2n) or O(n) For LinkedList get(int index) is O(n) add(E element) is O(1) // main benefit of LinkedList Concatenating (addall) O(1) // main benefit add(int index, E element) is O(n) remove(int index) is O(n)