contracts java interfaces · java contracts. superfriends video game! you’ve been hired to work...

Post on 18-Oct-2020

0 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Interfaces:JAVA CONTRACTS

SuperFriends Video Game!

You’ve been hired to workon the brand-new Super Friends videogame!

Mrs. Fronk wrote a SuperMan Class

Her job was to create properties and behaviors thatSuperman would possess.

Mrs. D wrote a WonderWoman Class

It has methods and instance variables that describe Wonder Woman.

Your Job: Class “defeatPrometheus”

You’re in charge of a class that plays out a battle with thevillain, Prometheus. Superman and Wonder Woman are both characters that playersmight use in this scene.

Fly!!!

A big part of the battle involves the characters flying around Prometheus and attacking him.● Superman flies by jumping into the air● Wonder Woman uses a cool invisible plane to fly

You carve out time at 1AM to code● You can’t see Mrs. Fronk’s code, or Mrs. Donaldson’s

code, but you know that you can instantiate a Superman Object and a WonderWoman Object using the default constructor○ Superman clarkKent = new Superman();○ WonderWoman Diana = new WonderWoman()

● Now you’re ready to make clarkKend and Diana fight Prometheus!

You start with Superman

You try to make him fly by trying to guess the name of Mrs. Fronk's flying method : clarkKent.Fly(); clarkKent.TakeOff(); clarkKent.Soar(); ……….but nothing works :(

You have to CALL Mrs. F at 2:00 AM to ask what she named the method “Oh! Sorry! It’s called: itsABird()”

Now you know: clarkKent.itsABird();

Now you try the same thing for Wonder Woman

WonderWoman Diana = new WonderWoman();Diana.Fly();Diana.ItsAPlane();Diana.Invisible();

Nothing Works

Now you have to call Mrs. D…

“Oh Sorry! It’s invisibleJet()”Now you can code!

Clark.itsABird();Diana.invisibleJet();

But that took WAY too long. Surely there’s a better way...

Syntax : INTERFACE● An INTERFACE is like a CONTRACT among

programmers● It’s an agreed-upon list of methods and

properties that a team uses when they’re working on the same project.

● It establishes common names so that cooperation is easy.

Interface SuperHero public Interface Superhero { public void fly();

public int getHealth(); //what are some other handy methods??}These are ABSTRACT methods, just suggestions.Each class that implements this interface must make them CONCRETE, or fully coded.

Syntax: implementA class implements an interface: class Superman implements Superhero //That means we know this class has a method called fly

public void fly(){

out.println (“I’m a bird! I’m a plane! I’m Superman!”);}

WonderWoman and Batman, too:

//Class Wonderwoman public void fly(){

out.println (“Into the jet!”);}

//Class Batman public void fly(){ out.println (“My cape is out!”);}

Here’s the cool part!!!

If I add IMPLEMENT different classes with the SAME interface● public class WonderWoman implements Superhero● public class SuperMan implements Superhero● public class Batman implements Superhero● public class SuperGirl implements Superhero● public class Aquaman implements Superhero

THEN I can INSTANTIATE THEM ALL AS THE SAME TYPE OF INTERFACE

● Superhero Diana = new WonderWoman();● Superhero clarkKent = new Superman();● Superhero bruceWayne = new Batman();● Superhero lindaDanvers = new SuperGirl();● Superhero michaelPhelps = new Aquaman();

And then I can put them in an array!

Superhero[] superFriends = new Superhero[5];superFriends[0] = diana;superFriends[1] = clarkKent;superFriends[2] = bruceWayne;superFriends[3] = lindaDavers;superFriends[4] = michaelPhelps();

I can even skip the naming part and instantiate new Superheros like this

Superhero[] superFriends = new Superhero[5];superFriends[0] = new Superman();superFriends[1] = new WonderWoman();superFriends[2] = new Batman();superFriends[3] = new SuperGirl();superFriends[4] = new Aquaman();

I can make them all fly because it’s in the interface. The array will call each type’s individual fly() method.

CodeSuperFriends[0].fly()

SuperFriends[1].fly()

Output“It’s a bird! It’s a plane! It’s Superman!”

“Into the jet!

They can also call their GetHealth methods

CodeSuperFriends[3].getHealth()

SuperFriends[4].getHealth()

Output“SuperGirl is healthy and strong at 9/10”

“Aquaman is about to drown at 1/10!!!”

Interfaces are a huge part of POLYMORPHISM

Polymorphism’s goal is to have the same method name be useful to many different types. It makes different types ACT alike.

Drawings to explain Worksheet 4, #1

int x, y; D constructor P //set x = 7,y =0 S constructor P// set x = v, y =7fun // return x as doublego // calls back()whoot // calls go()back // set x = 992toString //return class Name, x, y

four

P one = new P();out.println(one.fun());one.go();one.whoot();out.println(one + “\n\n”);

7.0

P 992 0

int x; D constructor Q // set x to 23D constructor Q // set x to 33, y to 0fun // return xgo // calls back()back // sets x = 45toString //return className + x+ super.toString()

P - SUPER CLASS Q - SUB CLASS extends P

Drawings to explain Worksheet 4, #2

int x, y; D constructor P //set x = 7,y =0 S constructor P// set x = v, y =7fun // return xgo // calls back()whoot // calls go()back // set x = 992toString //return getName(), x, y

one

P one = new Q();out.println(one.fun());one.go();one.whoot();System.out.println(one);//calls toString for one

23.0

Q 45 Q 7 0

int x; D constructor Q // set x to 23D constructor Q // set x to 33, y to 0fun // return x as a doublego // calls back()

back // sets x = 45toString //return className + x+ super.toString()

P - SUPER CLASS Q - SUB CLASS extends P

● getClass() and getName() are part of the Object class

● Every class extends the Object class

● So it is always overridden

Drawings to explain Worksheet 4, #2

int x, y; D constructor P //set x = 7,y =0 S constructor P// set x = v, y =7fun // return xgo // calls back()whoot // calls go()back // set x = 992toString //return getName(), x, y

one

P one = new Q();out.println(one.fun());one.go();one.whoot();System.out.println(one);//calls toString for one

fun // return x as a doublego // calls back()

back // sets x = 45toString //return className + x+ super.toString()

P - SUPER CLASS Q - SUB CLASS extends P

● getClass() and getName() are part of the Object class

● Every class extends the Object class

● So it is always overridden

Syntax: Facts about interfaces

1) All methods in an interface must be abstract2) All variables must be constant3) Interfaces cannot be instantiated4) Interfaces cannot contain constructor

methods5) Interfaces are abstract classes - just ideas of

what should happen

AP TRICK!!!!! YOU CANNOT instantiate an interface

NO: ● Superhero Diana = new Superhero();

○ //This means Diana only has abstract methodsYES:● Superhero Diana = new WonderWoman();

○ //This means Diana has her own Wonderful Way of performing the abstract methods in SuperHero

OK to have a final variable that is shared by all classespublic Interface Superheroes

No:● public int health;● String name;YES:● String headquarters = “Hall of Justice”; //common to all● int year = 2017;

Warm-Up: Let’s Practice!

Write your own interface:● You work in a zoo! ● Write an interface for program ZooKeeper. ● It should include 5 methods that must be

implemented in every Animal Class (like Lion, Elephant, Peacock, etc.)

● Include a final variable with the zoo name

public interface ZooKeeper{

String zoo = “San Francisco”

public String getName(); public String getSpecies();public String whatSound();

Common Interface: Comparable

public interface Comparable{ int compareTo(Object obj)}//Any class that implements Comparable must include a method that compares objects of that class.

Why do we need comparable?

It’s important so that JAVA has a way to sort Objects.

For example, we get to decide how to compare two Superheroes.

public int compareTo(Object obj)//We’ll find the difference in health points of 2 superheroes{ Superhero other = (Superhero) obj; int difference = this.getHealth() - other.getHealth(); return difference;}//Runner. If Superman’s health is 4 and WW’s is 7, what would be returned? Clark.compareTo(Diana); ________

Other Common Interfaces/

public interface Locatable{

public int getX(); public int getY();}

public interface Moveable{

public void setPos(int x, int y); public void setX(int x);

public void setY(int y);}

Sort Example

Monster[ ] monsters = new Monster[3];monsters[0] = new Monster(“Elmo”, 32, 6);monsters[1] = new Monster(“Cookie”, 48, 4);monsters[2] = new Monster(“Sully”, 721, 38);

Elmo326

Cookie484

Sully72138

monsters

I want to sort the Monsters, but can’t

Arrays.sort(monsters); //this returns an error!

What’s the problem?

Elmo326

Cookie484

Sully72138

monsters

JAVA doesn’t know how we want to sort

● Do we want to sort alphabetically by name?● Or in increasing order by weight?● Or in decreasing order by weight?● Or sort by age? ACK!

Elmo326

Cookie484

Sully72138

monsters

We need to select our own sort critiera:

● Let’s pick increasing order by age.● Lower ages come before higher ages● Let’s write the code.

Elmo326

Cookie484

Sully72138

monsters

public int compareTo(Object o) {

public int compareTo(Object obj) { Monster other = (Monster) obj;

int difference = this.getAge() -other.getAge(); return difference;

}

Elmo326

Cookie484

Sully72138

monsters

Syntax - words in red ALWAYS THE SAME

public int compareTo(Object obj) { Monster other = (Monster) obj; //cast to the type you’re comparing int difference = this.getAge() -other.getAge(); //get the variable to compare

return difference;}

Elmo326

Cookie484

Sully72138

monsters

Now one monster can compare himself to another!

What would be output if Elmo is 6 and Cookie is 4 and Sully is 721?

Elmo.compareTo(Cookie); _____Elmo.compareTo(Sully); _____

Even better to use the array monsters

//What would be output?mosters[0].compareTo(monsters[1]); _____mosters[0].compareTo(monsters[1]); _____

Elmo326

Cookie484

Sully72138

monsters

NOW Collections.sort(monsters will work)

Because the sort() method will know how to compare one monster to the other.If compareTo() returns a positive number, sort will switch the elements.6-4 = 2, so Elmo and Cookie will switch.

Elmo326

Cookie484

Sully72138

monsters

math Example of Interface:You write an interface when you know WHAT you want to be done without knowing HOW.

public interface Circles{ public abstract int findCircumference(Object obj); //abstract implied, the word is optional private static final int pi = 3.1415; //variables must be private static final}

We can use them both!

class Ship implements Locatable, Moveable{ private int xPos, YPos; //How many methods have to be written?}

Fast Facts: Syntax● All methods in an interface must be public abstract.● All variables in an interface must be public static final● An interface cannot be instantiated● Interfaces cannot contain implemented (written)methods● Interfaces are considered to be purely abstract classes

top related