Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1

2 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?

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

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

5 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

6 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

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

8 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);... }

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

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

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

12 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

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

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

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

16 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

17 Collections (Data Structures)

18 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)

19 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

20 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

21 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?

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

23 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?

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

25 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

26 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")); }

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

28 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

29 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?

30 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

31 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

32 Linked Lists Another type of list in our collections

33 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

34 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

35 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()

36 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”); }

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

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

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

40 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…

41 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);

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

43 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

44 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)


Download ppt "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."

Similar presentations


Ads by Google