JAVA INTERFACES

¡Supera tus tareas y exámenes ahora con Quizwiz!

if a class extends a interface, what relationship do they have? what is the concept called?

"is-a" relationship; the class is-a interface. Polymorphism(a variable of the supertype can refer to a subtype object).

What is important to know about interface methods and interface references?

-BUT ONLY THE INTERFACE METHODS ARE ACCESSIBLE THROUGH THE INTERFACE REFERENCE -Even though a single class may implement many interfaces, if it is being accessed through an interface variable, the methods in the other interfaces are not avaliable -The interface masks the object such that only the interface methods are visible / callable -if other methods are attempted to be accessed, a compliation error will result

What is important if you decide to use interfaces for methods?

-In the class header we must declare that the interfaces are implemented public class Comedian implements Laughable, Booable { public void laugh() { System.out.println("ha ha ah");} public void boo() { System.out.println("you stink!");} }

How do you want to identity an object in multiple ways?

-One based on its inherent nature (i.e. its inheritance chain) Ex: A person -Classes are used to identity objects in this way -Others based on what it is capable of doing EX: A swimmer, A musician, A performer, so on and so forth -Interfaces are used to identify objects in this way

How do you implement an interface: i.e. how do you say in Java "this class is going to use XYZ interface"?

1. You use the "implements" keyword: public class DeskPhone implements ITelephone { 2. You actually implement ALL of the interface methods: The declaration line (ABOVE) will remained underlined in red (an error) until ALL the interface's methods are implemented.

What is an interface?

A java Interface is a named set of methods -However, no method bodies are given -- just the headers -Static constants are allowed, but no instance variables are allowed -Any Java class (no matter what its inheritance) can implement an interface by implementing the methods defined in it -Essentially an interface is stating an ABILITY of the class -A given class can implement any number of interfaces

Public is redundant for an interface because...

All the method signatures defined here HAVE to be used in a different class: Methods from an interface HAVE TO BE public to be used!

public class Gearbox { private boolean clutchIsIn; public void operateClutch(boolean inOrOut) { this.clutchIsIn = inOrOut; } } In this class and method, the code can be changed anytime; we haven't made any standard, any COMMITMENT that it won't be changed. An interface is...

An interface IS a commitment that the methods you have created will STAY THE SAME: it kind of "locks" them in. It is a "contract" that the method's signatures and variables in the interface's constants will NOT CHANGE. As long as you stick to what's in the interface that you've created- you WILL NOT be breaking code anywhere.

What can an interface variable do?

An interface variable can be used to reference any object that implements that interface./ -Note that the same method name (ex: laugh() below) may in fact represent different code segments in different class

what happens when there are default methods in the interface?

Any class that implements the interface will already have the method defined and usable.

Explain the example given about the Comparable interface.

Comparable interface contain one method : int compareTo(Object r); -Returns a negative number if the current object is less than r, 0 if the current object equals r and a positive number if the current object is greater than r -Consider what we need to know to sort data -is A[i] less than, equal to or greater than A[j] -Thus, we can sort Comparable Data without anything else about it -Polymorphism allows this to work!

Remember: you don't actually create the full methods in an interface. You simply...

Define the methods: You just create the method "signature" here (otherwise known as method "stubs"): public interface ITelephone { public void powerOn(); public void dial(int phoneNumber); public void answer(); public boolean callPhone(int phoneNumber); public boolean isRinging(); } The code itself is DEFINED in the actual class. What we have defined here now is the CONTRACT with the PARAMETERS that makes sure that the method signature will not change!

How do you instantiate an object that implements an interface (in the main method)?

EXAMPLE: ITelephone timsPhone; timsPhone = new DeskPhone(2385623); OR: DeskPhone timsPhone; timsPhone = new DeskPhone(2385623); THE IMPORTANT THING TO REMEMBER IS: You cannot instantiate an ITelephone object on it's own: REMEMBER: It just TELLS the other (actual) classes what methods to use/override

Example of using interface methods and interface references.

Ex: Laughable [] funny = new Laughable[3]; funny[0] = new Comedian(); funny[1] = new SitCom(); //implements laughable funny[2] = new Clown(); //implements laughable for(int i = 0; i < funny.length; i ++) funny [i].laugh(); funny[0].boo(); //illegal even though Comedian[0] it has the boo() method

In terms of classes and methods, what can interfaces allow programmers to do?

Ex: public interface Laughable { public void laugh();} public interface Booable { public void boo ();} -Bascially any Java class can implement Laughable by implementing the method laugh() -Same for method boo

Runnable

Example Lambda: () -> System.out.println("Doing stuff")

Supplier

Example Lambda: () -> new String("Hello ladies!')

Callable

Example Lambda: () -> {new Double(3.141597); throw new Exception(); }

Function

Example Lambda: (Integer num) -> num.toString()

BiFunction

Example Lambda: (Integer num1, Double num2) -> Double.toString(num1.doubleValue()/num2)

BiPredicate

Example Lambda: (Number num1, Number num2) -> num1.doubleValue() > num2.doubleValue()

Comparator

Example Lambda: (a, b) -> a-b

BinaryOperator

Example Lambda: (a,b) -> a + b

BiConsumer

Example Lambda: (key, value) -> System.out.println( "Key: " + key + "\t" + " Value: " + value )

Comparable

Example Lambda: b -> this.id - b.id

Predicate

Example Lambda: num -> num % 2 == 0

Consumer

Example Lambda: stuff -> System.out.print(stuff)

UnaryOperator

Example Lambda: x -> x*2

Function

Example Method Reference: Integer::toString

Predicate

Example Method Reference: List::isEmpty

BinaryOperator

Example Method Reference: String::concat

Supplier

Example Method Reference: String::new

UnaryOperator

Example Method Reference: String::toUpperCase

Consumer

Example Method Reference: System.out::print

static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); }

Go make a method that uses a Collection and an Iterator (flipside for example)

Interfaces are closely related to....?

Interfaces are closely related to inheritance and polymorphism. -The interface acts as a supercalss and the implementing classes implement the actual methods however they want -An interface variable can be used to reference any object that implements that interface -However, only the interface methods are accessible through the interface reference

what is an interface?

It is a reference type(similar to a class)

In Java, what is the restriction of using inheritance?

Java allows only single inheritance -A new class can be a subclass of ONLY ONE parent (super) class -There are several reasons for this, from both the implementation (i.e. how to do it in the complier and interpreter) point of view and the programmer (i.e. how to use it effectively) point of view -However, it is sometimes useful to be able to access an object through more than one superclass reference

Function

Method Signature: R apply(T t)

BiFunction

Method Signature: R apply(T t, U u)

UnaryOperator

Method Signature: T apply(T t)

BinaryOperator

Method Signature: T apply(T t1, T t2)

Supplier

Method Signature: T get()

Callable

Method Signature: V call() throws Exception

Predicate

Method Signature: boolean test(T t)

BiPredicate

Method Signature: boolean test(T t, U u)

Comparator

Method Signature: int compare(T t1, T t2)

Comparable

Method Signature: int compareTo(T t)

Consumer

Method Signature: void accept(T t)

BiConsumer

Method Signature: void accept(T t, U u)

Runnable

Method Signature: void run()

What is the common naming practice for interfaces?

Naming your interface class starting with I: ITelephone, IShoes, IBag, etc... NOTE: Tim later retracts this statement! It may be appropriate in some cases if you have other classes with similar names, but in general, it sounds like this isn't used much anymore.

Explain the note about static constants in a java interfaces.

Since Java 8 interfaces are allowed to have default methods. These are methods that are defined within the interface and that become part of any class that implements the interface. Interfaces may also have static methods. These are similar to static methods within classes.

How do you set up an interface in IntelliJ?

The same as setting up a class: - Go to the folder that you want, - right click - Select new, then class - UNDER the area where you name your class is a menu: Select INTERFACE - Name your interface class starting with an "i": ITelephone

what are the non-default or non-static methods in the interface called?

They are public abstract methods

In IntelliJ, how do we implement the methods from an interface (within the actual class we've created)?

Use the generate menu: Alt+insert (fn+Alt+insert on my laptop) NOTE: If not ALL of the methods from our interface have been implemented, it will NOT be a valid class! Using our telephone example: When we IMPLEMENT the interface we're saying "If you want to create a valid telephone object, it MUST contain/use all the methods we've defined; otherwise, it is NOT a valid telephone object." In our case- even though a desktop phone will always have the powerOn()- there's really no "power" button on a desktop phone- you MUST implement the method!

Runnable

Used by: Executor.execute(), new Thread( ),ExecutorService.submit()

Callable

Used by: ExecutorService.submit(), not by ExecutorService.execute()

Supplier

Used by: Stream.collect() Stream.generate()

Predicate

Used by: Stream.filter(), Stream.allMatch(), Collection.removeIf()

Consumer

Used by: Stream.forEach(), Stream.peek()

UnaryOperator

Used by: Stream.iterate(), List.replaceAll()

Function

Used by: Stream.map(), Stream.flatmap(), Comparator.comparing()

BinaryOperator

Used by: Stream.reduce() one argument version

What are interfaces? What does an interface do/allow us to do?

WHAT IS AN INTERFACE: An interface specifies methods that a particular class (which implements the interface) MUST use. The interface itself is ABSTRACT: this means there is no actual code for any of the methods IN the interface- you just provide the method names/parameters. The actual code still goes in the CLASS that you're creating. WHAT IT ALLOWS US TO DO: The idea is to use an interface to provide a common behavior that can be used by several classes by having them all implement the same interface. This is a way to STANDARDIZE the way a particular SET OF CLASSES is used.

The List class IS an interface class, meaning that it is abstract. What does this mean for, say, the LinkedList challenge (videos 69-71) where we (obviously) used LinkedLists for our playlist example (Hint: interfaces have a SET of classes)?

We can easily change all of the LinkedList<> declarations to List/Arraylist, and it will still work! Why? Because with an interface class (List), ALL "subclasses" MUST implement ALL of the methods of the interface class! (See video 73 "Interfaces Part 2" or "Interfaces LinkedList" file). You can see with this example, Java uses interfaces internally with A LOT of their code: it's a good way to make your code efficient, clean, etc ...

Comparable interface: Think of the objects we want to sort as "black boxes"

We know we can compare them because they implement Comparable -We know we can compare them because they implement Comparable -We don't know (or need ot know) anything else about them -Thus, a single sort method will work for any array of any Comparable class

where do we write the keyword to use the interface in the class? how do we write it?

We use the keyword 'implements' at the class header eg public class Class implements Implement1,Implement2 { variables, cstor, methods }

How does it benefit us to be able to access objects through interfaces?

_Sometimes we are only concerned about a given property of a class -The other attributes and methods still exist, but we don't care about them for what we want to do -For example: Sorting -We can sort a lot of different types of objects like:Various numbers;People based on their names alphabetically; Employees based on their salaries -Each of these classes can be very different; however, something about them all allows them to be sorted

How does it benefit us to be able to access object through interface? continue with sorting.

_They can be compared to each other -So we need some method that invokes this comparison -In order to sort them, we don't need to know or access anything else about any of these classes -Thus, if they all implement an interface that defines the comparison, we can sort them all with a single method that is defined in terms of that interface -Think about comparable interface

Collection

a List is a special kind of ___________

Collection

a Set is a special kind of ___________

Set

a SortedSet is a special kind of __________

a constructor that takes a Collection argument

by convention, what do general-purpose Collection implementations have?

public static <E> void swap(List<E> a, int i, int j) { E tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); }

create a function using the List interface and its operations, that swaps two indexed values of a List

listObj.size();

how do you return the number of elements in a List?

List<Type> list3 = new ArrayList<Type>(list1); list3.addAll(list2);

how would you add one list to the end of another? (non-destructive)

String[] x = y.toArray(new String[0]); //y is a Collection

how would you turn a Collection of String objects, into a String array?

Object[] x = y.toArray(); //y is a Collection

how would you turn a collection into an array?

What is the keyword required to use Interfaces(case sensitive)

implements

positional access; search; iteration; and range-view

in addition to the operations from Collection, what does the List interface add?

learn more...

interator COllceiotn

what are the modifiers of the methods in the interface set to?

public abstract

what modifiers do the data fields in an interface have?

public static final

how do interface inherit interfaces? if a class implements the interface what methods must it define?

the interface inherit other interfaces by extending them. If a class implements the interface, it would have to define all the abstract methods of all the interfaces.

Since interfaces cannot be instantiated, what can be done to them?

we can implement interfaces to classes or extend(inherit) them to other interfaces

myCollection.add(E element); //E being whatever type the Collection contains

what Collection method adds a new element?

myCollection.isEmpty();

what Collection method checks if the group is empty?

myCollection.contains(Object element);

what Collection method checks the group for a given object?

get, set, add, remove

what are the positional operations of the List interface?

a group of objects; known as elements

what does a Collection represent?

returns true if iteration has more lements

what does the Iterator method, hasNext(), do?

return next element in iteration

what does the Iterator method, next(), do?

removes the last element returned by next()

what does the Iterator method, remove(), do?

public interface Iterator<E> { boolean hasNext(); E next(); void remove(); //optional }

what interface does a Collection have that allows you to traverse through a collection and remove elements selectively?

for(Object o : collection){ System.out.println(o); }

what is the 'for' method for iterating over a collection?

to pass around objects where maximum generality is desired

what is the general rule for using Collection(s)?

obtaining a stream and performing aggregate operations on it

what is the preferred method of iterating over a collection?

list1.addAll(list2); //destructively means destroying both lists, and creating a new one

what would you do if you wanted to add one list to the end of another? (destructively)

removing the current element; iterating over multiple collections in parallel

when should you use Iterator over for-each, regarding Collections?


Conjuntos de estudio relacionados

CHAPTER 16 SLEEP DISORDERS AND TREATMENT

View Set

Complementary and Integrative Health

View Set

Chapter 47: Management of Patients With Intestinal and Rectal Disorders, Prep U--Ch. 47: Mgmt of Patients With Intestinal and Rectal Disorders

View Set

Chapter 7: Entrepreneurship and Starting a Small Business

View Set