
Understanding Interfaces in Java: Methods and Implementations
Explore how interfaces in Java define the interactions between objects, the role of abstract methods, and how classes implement interfaces to enforce method definitions. Learn how interfaces provide a way to define common activities across unrelated classes and how object references are tied to interface types.
Uploaded on | 0 Views
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
CSC 1052 Algorithms & Data Structures II Lists and Interfaces
Interfaces The public methods of an object defines how it interacts with the rest of the system A Java interface formalizes this idea by establishing a set of operations that a class will support This is a system interface, as opposed to a user interface An interface contains abstract methods, which establishes the header of the method (name, return type, parameter list) An abstract method does not define the code that will be executed when the method is called 3
Interfaces In the interface, the method header is simply followed by a semicolon public interface Printable { void printSummary(); void printAll(); } Like a class, an interface is usually defined in its own file (Printable.java) It compiles into bytecode (Printable.class) 4
Interfaces An interface cannot be instantiated Instead, it is implemented by one or more classes public class Person implements Printable { // must define printSummary and printAll } A class must provide a definition (code) for all methods listed in any interface that it implements This is enforced at compile time 5
Interfaces Multiple classes can implement the same interface public class Stock implements Printable { // must define printSummary and printAll } There is no relationship between the Person and Stock classes, except that they are both Printable Interfaces provide a way to define common activities on otherwise unrelated classes 6
Interfaces An interface name can be used as the type of an object reference variable Printable p = new Stock(); A Printable reference can refer to any object of any class that implements the Printable interface So we could later reassign the reference p to a Person object p = new Person(); 7
Interfaces Using an interface reference restricts how we can interact with an object The compiler will only allow operations that it knows are valid So if p is a Printable reference, the compiler will only allow it to be used to call printSummary or printAll p.printAll(); Even if p is pointing to a Person, which has a getName method, the compiler will flag this as an error: name = p.getName(); 8
Interfaces A cast can be used to force the reference to be treated like a particular class name = ((Person)p).getName(); The will result in an exception during runtime if the reference isn't actually pointing to a Person object You can check using the instanceof operator if (p instanceof Person) name = ((Person)p).getName(); 9
Interfaces A class can implement multiple interfaces public class Stock implements Printable, Membership, Comparable { // must define all methods of all interfaces } The Comparable interface is defined in the Java API 10
Interfaces Summarizing the comparison of classes and interfaces: A class can be instantiated, but an interface cannot An interface does not have constructors Methods of an interface are abstract and public An interface can contain static, final constants Both classes and interfaces can be used as reference types A class can implement multiple interfaces 11
Lists A list collection is a sequence of items of the same data type. Items can be added, removed, or set anywhere in the list. The list grows and shrinks as needed to hold any number of items. 13
List Operations add Inserts a new element between to other elements in the list, or at the top or bottom, increasing the length by one remove Extracts an existing element from the list, decreasing the length by one set Replaces an element in the list with a new one, so the length doesn't change size Reports number of elements in the list isEmpty Returns true if list is empty, false otherwise Learn more about list operations in the Java API. 14
The List Interface The List interface defines how a list behaves using abstract methods. It's up to a specific class to implement the interface. Two Java API List classes that do this are: Each List is generic class. You specify its type when declared: List<String> names = new ArrayList<String>(); List<Person> members = new ArrayList<Person>(); 15
Lists: Adding Items Adding elements to a list is done with one of the add methods. Iterating the elements can be done with a for-each loop List<String> beatles = new ArrayList<String>(); beatles.add("John"); beatles.add("George"); beatles.add("Ringo"); beatles.add(1, "Paul"); // inserts at index 1 for (String name : beatles) System.out.println(name); John Paul George Ringo 16
Lists: Getting Items Getting elements from a list is done with the get method. List<String> numbers = new ArrayList<String>(); numbers.add("one"); numbers.add("two"); numbers.add("three"); numbers.add("four"); System.out.println(numbers.get(2) + " at index 2"); three at index 2 17
Lists: Removing Items To remove an element from a list use the remove method. List<String> beatles = new ArrayList<String>(); beatles.add("John"); beatles.add("Paul"); beatles.add("George"); beatles.add("Ringo"); beatles.remove(0); // removes item at index 0 for (String name : beatles) System.out.println(name); Paul George Ringo 18
Lists: Setting Items To set an element in a list to a new value use the set method. List<String> beatles = new ArrayList<String>(); beatles.add("John"); beatles.add("Paul"); beatles.add("George"); beatles.add("Ringo"); beatles.set("Britney", 1); // sets item at index 1 for (String name : beatles) System.out.println(name); John Britney George Ringo 19
Lists: How Many Items To find out if a list is empty or how many items it contains, use the isEmpty and size methods. List<String> beatles = new ArrayList<String>(); System.out.println("Empty? " + beatles.isEmpty()); beatles.add("John"); System.out.println("Empty? " + beatles.isEmpty()); beatles.add("Paul"); beatles.add("George"); beatles.add("Ringo"); System.out.println("How many? " + beatles.size()); Empty? true Empty? false How many? 4 20
Example: Deck of Cards The problem of representing a 52-card deck of cards is well- suited to an ArrayList and related Java Collections support. private List<Card> deck = new ArrayList<Card>(); This example assumes there is a Card class representing a card. public class Card { public Card(String cardRank, String cardSuit) { rank = cardRank; suit = cardSuit; } } 21
Example: Deck of Cards The constructor initializes the deck: public DeckOfCards() { String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"}; String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"}; for (String rank : ranks) for (String suit : suits) deck.add(new Card(rank, suit)); } 22
Example: Deck of Cards Shuffling relies on the shuffle method in the Collections class. public void shuffle() { Collections.shuffle(deck); } Dealing is done by simply taking the first (0th) card. public Card dealCard() { Card card = null; if (deck.size() > 0) card = deck.remove(0); return card; } 23
Example: Deck of Cards Here is the beginnings of a game program that starts with dealing the top 5 cards from the deck: DeckOfCards deck = new DeckOfCards(); deck.shuffle(); System.out.println("Deal the top five cards:"); for (int count = 1; count <= 5; count++) System.out.println(deck.dealCard()); 7 of Spades 4 of Hearts 2 of Hearts Queen of Hearts 8 of Clubs 24
Arrays of Objects An array can have elements that are primitive values or objects. An array of objects uses the class name as the element type. Creating an array of objects looks like this: String[] words = new String[5]; This array is declared to hold 5 strings, but it doesn't have any values yet. 25
Filling an Array To fill the array of objects, an object is assigned to each element of the array, like this: words[0] = "hullaballoo"; words[1] = "sozzled"; words[2] = "lollygag"; words[3] = "flabbergast"; words[4] = "skirl"; Since array indexes are numbered starting with 0, the last element is 1 less than the length of the array. 26
Iterating an Array To iterate through the array of objects, the for-each loop makes it simple: for (String word : words) System.out.println(word.toUpperCase()) Each element in turn is assigned to word, converted to uppercase, and then printed. HULLABALLOO SOZZLED LOLLYGAG FLABBERGAST SKIRL 27
Another Initilization An initialization list is an alternate way to create a fill an array of objects. String words[] = {"hullaballoo", "sozzled", "lollygag", "flabbergast", "skirl" }; This allows the array to be created and initialized in a single step. 28
Arrays of Person Objects Here's another example where an array of objects contains Person objects rather than strings: Person[] athletes = new Person[4]; athletes[0] = new Person("Michael", "Jordon"); athletes[1] = new Person("Babe", "Ruth"); athletes[2] = new Person("Martina", "Navratilova"); athletes[3] = new Person("Wayne", "Gretzky"); for (Person athlete : athletes) System.out.println(athlete.getLastName() + ", " + athlete.getFirstName()); The array is created, initialized, and the elements are printed. 29
Big Numbers There are limits to the values each primitive data type can store. The biggest value a long data type can old is: 9223372036854775807 In Java, the BigInteger class can work with much larger values BigInteger a = new BigInteger("98765432198765432198765432109876543"); BigInteger values can be any value in the range: -22147483647 to 22147483647 31
Big Numbers Instead of using +, -, *, /, and % with BigIntegers, you call the add, subtract, multiply, divide, and remainder methods. BigInteger a = new BigInteger("987654321987654321987654321"); BigInteger b = new BigInteger("123"); BigInteger c = a.multiply(b); System.out.println(c); The output of this code is: 121481481604481481604481481483 32
Big Numbers A factorial can be calculated like this: BigInteger factorial = BigInteger.ONE; BigInteger num; for (int i = 2; i <= 50; i++) { num = new BigInteger(i + ""); factorial = factorial.multiply(num); } System.out.println("50! is " + factorial); And its output: 50! is 30414093201713378043612608166064768844377641568960512000000000000 33
Big Numbers A double in Java only stores 15 significant digits. The BigDecimal class is only limited by your computer's memory. BigDecimal x = new BigDecimal("0.123456789123456789123456789"); BigDecimal y = new BigDecimal("99.99"); BigDecimal z = x.divide(y, 30, RoundingMode.ROUND_UP); System.out.println(z); Resulting in this output: 0.001234691360370604951729740865 There are a few rounding modes that control how values are rounded. 34