Upload
others
View
13
Download
0
Embed Size (px)
Citation preview
(remedial)Java
1 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packages
2 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packages(1)
package path.to.package.foo;
▪ Eachclassbelongstoapackage
▪ Packagesgroupsclassesthatserveasimilar
purpose.
▪ Packages:
▪ Helpavoidclasseswiththesamename
▪ Classesinotherpackagesneedtobeimported
3 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packages(2)
package path.to.package.foo;
▪ Arejustdirectories(inthediskorjar)
▪ Forexampleclass3.inheritanceRPGislocatedin
<workspace>\RemedialJava\src\class3\inheritenceRPG
▪ Thecompiledclassesunder…\RemedialJava\bin\...
4 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packages(3)
▪ Definingpackages
theclassfullnameispackage.ClassName(iepath.to.package.foo.Foo
package path.to.package.foo;class Foo {}
5 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packages(2)
▪ Definingpackages
▪ Usingpackages
package path.to.package.foo;class Foo {}
import path.to.package.foo.*;import path.to.package.foo.Foo;
6 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packagesexample
package neighborhood;
public class Car {}
package neighborhood;
public class Road {}
7 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packagesexample
package citytools;
import neighborhood.Car;import neighborhood.Road;
public class City {public static void main (String[] args){
Car car = new Car();car.move(30);
}}
8 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Packagesexample
package citytools;
// import neighborhood.Car;// import neighborhood.Road;
public class City {public static void main (String[] args){
neighborhood.Car car = new neighborhood.Car();car.move(30);
}}
9 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Whypackages?
▪ Combinesimilarfunctionality
▪ Separatesimilarnames
Convention(domain.society.project.modules)
fr.upsud.libraries.Libraryfr.upsud.libraries.Book
shopping.Listpacking.List
fr.upsud.remedialjava.class3
10 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Whypackages?
▪ Allclasses“see”classesinthesamepackage(no
importneeded)
▪ Allclasses“see”classesinjava.lang
▪ Suchas:java.lang.String; java.lang.System▪ JavahasaLOTofpackages/classes.Reusethemto
avoidextrawork(useyourjavaversion)
▪ http://docs.oracle.com/javase/10/docs/
11 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Collections
12 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
RememberourLibrary
▪ Whatwouldhappenifwewantedamorethan10
books?Evenbetter,alibrarythatwecanperiodically
addbookstowithoutworryingaboutitsstorage?
public class Library {
private Book[] _allBooks = new Book[10];
…}
13 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Objectcollections:ArrayLists
▪ Javacomeswithseveralcollections,i.e.,objects
thatrepresentagroupingofotherobjects.
ExamplesincludeArrayLists,Sets,Maps,etc.
(seeJavaAPIoncollectionsformoreinfo)
ArrayList:Modifiablelist(internallyimplementedwithArray)
▪get(index)toaccessitematindex(notarray[i])
▪Add/deleteitems(nosizerestriction)
▪Loopoveritems
14 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
ArrayListexample
public class ArrayListExample { public static void main(String[] arguments) {
ArrayList<String> someStrings = new ArrayList<String>(); // creation
// adding as many items as we wantsomeStrings.add("Alice");someStrings.add("Bob");someStrings.add("Steve");
System.out.println( "Size is " + someStrings.size() ); // can get its size
System.out.println(someStrings.get(0)); // can get items in index position 0 System.out.println(someStrings.get(5) ); // error when outside
for (int i = 0; i < dishes.size(); ++i ) // loop using indexSystem.out.println(someStrings.get(i));
dishes.set(2, "Peter");// replace item at index
for (String s: someStrings) // another loop over collectionSystem.out.println( s ); // that gives us references
}}
15 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Exercise1(partone&two)https://www.lri.fr/~anab/teaching/remedialJava/ex-session3.pdf
Reminder:
▪ Importclassesfromotherpackagesusingimportpackage.classname;
▪ ArrayList:
▪ ArrayList<Class> someName = new ArrayList<Class>();
▪ get(index):returnsobjectinindexpos▪ set(index,object):setsobjectinindexpos
▪ add(object):addsanobjectattheendoftheArrayList
▪ remove(?):removesobjectateitherindex,orobjectitself
▪ Loopusingindex,oroverelementsfor(Class c: someCollection)
16 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Objectcollections:Maps
▪Storesa(key,value)pairofobjects▪Lookupthekey,getbackthevalue▪Keyneedstobeunique
Example:
▪Addressbook:mapnametoemailaddress
▪Menu:mapdishnumbertoDishobject
▪TreeMap(sorted),HashMap(pseudorandom)
17 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Mapexamplepublic class MapExample {
public static void main (String[] args){
HashMap<String,String> emails = new HashMap<String, String>(); // creation
emails.put("John", "[email protected]"); // adding entry of type String:Stringemails.put("Cat", "[email protected]");
System.out.println( emails.size()); // gets size
for (String k : emails.keySet()) // gets all keys System.out.println(k);
if ( emails.containsKey("John") ) // checks if key existsemails.replace("John", "[email protected]"); // replaces value
for (String v : emails.values()) // gets all values System.out.println(v);
if (!emails.isEmpty()) // checks if emptySystem.out.println("I have stuff!");
emails.remove("Cat"); // removes key
for (HashMap.Entry<String,String> pairs: emails.entrySet()) System.out.println(pairs); // iterates over all entries
}}
18 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Objectcollections:Maps
▪Mapsaregoodfordictionaries,look-uptasks
whenyouhaveuniqueids,andconvertions
(e.g.,checkMorseCodeexampleincode)
19 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abitmoreonmethods
20 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abitmoreonmethods
▪ Methods(includingconstructors)canbe
overloaded(multiplemethods,samename)
(onewayofensuringpolymorphisminJava)
public Car {this.Car("unknown", "white"); // I want a default value
}
public Car(String myname, String mycolor){name = myname; // or this.name = myname;color = mycolor; // or this.color = mycolor;
}
21 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Overloading
▪ Thecompilersearchesforthebestmethod,
basedontheTYPEoftheargumentspassed
public class PrintStream {public void println(String text){...}public void println(double value){...}
public static void main (String args[]){PrintStream out = System.out;out.println(“toto”);out.println(3.0);out.println(2);
}}
22 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Overloading
▪ ThereturnTYPEofthemethodisnotconsidered,
soitisimpossibletodifferentiatemethodsjustby
theirreturnTYPE
public class BadOverloading {public int f(){...}public double f(){...} // f is already defined in BadOverloading
public static void main (String args[]){BadOverloading bo = new BadOverloading();bo.f();
}}
23 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Overloading,whentouse?
▪ Weuseoverloadingwhenmethodshavethe
samesemantic(purpose),butdifferent
arguments
public class Math {public float sqrt(float value){…}public double sqrt (double value){…}
} // this is ok
public class List {public void remove (Object value) {…}public void remove (int index) {…}
} // if we want to be picky, this is NOT ok, why?
24 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Varargs
▪ Itispossibletodefinemethodswithvariable
numberofargumentsusingthenotation“…”
▪ Argumentsareputinatable
public static void main (String[] args) {System.out.printf(“%d\n”,2);
}
public class PrintStream {public void printf (String text, Object... args){
... // args is an ArrayList so we can run a loop
}}
25 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Varargs
▪ Varargsareconsideredastables,sowecannot
overloadvarargsandtables
public class VarargsOverloading {private static int min(int... array){ }
private static int min(double... array){ }
private static int min(int[] array){ } // min(int...) already defined in VarargsOverloading
}
26 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Exercise1(part3)www.lri.fr/~anab/teaching/remedialJava/ex-class3.pdf
Reminder:
▪ Syntexforvarargs
methodTYPE(otherinputparams,TYPE…name)
27 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Inheritance
28 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ ImagineaverysimpleRPGgame
public class Person {public String _name;public int _health = 100;public int _mana = 0;
public void sayName (){System.out.println(_name);
}
public void attackPerson(Person target){System.out.println(_name + " attacking " +
target._name); target._health -= 10;
}}
29 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ WenowwanttocreateaWizard
public class Wizard {// need to copy all of Person staff// booooring
}
▪ Whygointoallthetrouble?Wizardhasanddoes
everythingthatasimplePersondoes…
30 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ WizardisasubclassofPerson
public class Wizard extends Person {
}
31 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ WizardisasubclassofPerson
▪ Wizardcanuseeverything*thatPersonhas
e.g.,wizard1._health +=1;
▪ Wizardcandoeverything*thatPersoncando
e.g.,wizard1.attackPerson(person1);
▪ YoucanuseWizardasaPersontoo
e.g.,person1.attackPerson(wizard1);
*exceptforprivatefieldsandmethods(keywordprotectedmaybeused)
32 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ Let’simproveWizard
public class Wizard extends Person {
int _mana = 100;ArrayList<String> _spells;
public void cast (String spell){// do cool stuff here_mana -= 10;
}}
33 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ Canweinheritfrominheritedclasses?
public class GrandWizard extends Wizard {
public void sayName (){System.out.println("Grand Wizard" + name);
} //overriding (ancestor) parent method}
grandWizard1.name = “Gandalf”;grandWizard1.attackPerson (person1);grandWizard1.sayName();
34 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
HowdoesJavadothat?
▪ WhatJavadoeswhenitseesgrandWizard1.sayName();
▪ LookforsayName()inGrandWizard
▪ It’snotthere!DoesGrandWizardhaveaparent?
▪ LookforsayName()inWizard
▪ It’snotthere!DoesWizardhaveaparent?
▪ LookforsayName()inPerson▪ Gotit!CallsayName()andprintthefield_name
35 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Inheritancestructure
Person:
ParentofWizard,Elf,…
SubclassesofPerson
SubclassofWizard
Person
Wizard Fighter Elf
Grand
Wizard
36 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Canonlyinheritfromoneclass
Canonlyinheritfrom
oneparentclass
Multipleinheritance
notpossible…
Why?
Person
Wizard Fighter Elf
Wizard
Elf
IfbothWizardandElfimplement(differently)
sayName(),whichonedoesWizardElfcall?
37 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abasicinheritanceexample
▪ Adaptingmethodsfrominheritedclasses
public class GrandWizard extends Wizard {
public void sayName (){System.out.println("Grand Wizard" + name);
} //overriding (ancestor) parent method}
grandWizard1.name = “Gandalf”;grandWizard1.attackPerson (person1);grandWizard1.sayName();
38 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Exercise2-partone&twowww.lri.fr/~anab/teaching/remedialJava/ex-class3.pdf
Reminder:
▪ Partone
exampleofasingleclassdiagram
▪ Parttwo
inheritancebetweenclasses
class CHILDCLASS extends PARENTCLASS {}
achildclasscanoverride(i.e.,redefine)amethodfromaparent/
ancestorclassbyredefiningitinitsbody
Wizard
protectedArrayList<String>_spells
publicvoidsayName()
publicStringcastSpell()
39 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Aclassinheritsallthemembersoftheparent
(super)class,i.e.,allfieldsandmethodsandcan
usethemwithouthavingtodoanythingmore.
▪ AllexceptConstructors,thatarenotinherited
▪ Unlessthedefaultconstructorisused,constructorsneedtoberedefinedforeachchild(morelater).
40 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Methodsareinherited.
▪ Addingamethodofthesamenameasoneinasuper-classredefines(overrides)themethod.This
waywehaveimplementationsadaptedtothe
semanticsofthemethod.
class Person { public void sayName (){
System.out.println(_name); }}
class GrandWizard extends Wizard { public void sayName (){
System.out.println("GW" + _name); }}
41 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Fieldsareinherited
▪ Whenweaddafieldofthesamenameasoneinaparentclass,thefieldofthesuperclassisno
longervisibletous(wesayitishiddenormasked)
class Person { public int _name; public int sayName (){
System.out.println(_name); }}
class Wizard extends Person { public String _name; public String sayName (){
System.out.println("GW" + _name); }}
42 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Whatifwewanttoaccessmethodsorfieldsfrom
thesuperclass,whenwehaveoverriddenthe
methodsormaskedthefields(e.g.,usethe
sayName()ofPersonfortheGrandWizardZed?
43 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Weusethekeywordsuperclass Wizard extends Person {
public String sayName (boolean modest){if (modest)
super.sayName();else
System.out.println("GW" + _name); }}
44 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Weusethekeywordsuper
▪ Onlyworksforimmediateparentandnon-static
methods(theybelongtotheirclass)
class Wizard extends Person {
public String sayName (boolean modest){if (modest)
super.sayName();else
System.out.println("GW" + _name); }}
45 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Accesstoparentinformation
▪ Weusethekeywordsuper
▪ Constructorsarenotinherited.
▪ Unlessthedefaultconstructorisused,constructorsneedtoberedefinedforeachchild.
▪ Firstlineintheconstructorneedstobeacalltotheconstructoroftheparentclass,usingsuper
class Person { protected String _name; public Person(String n){ _name = n; }}
class Wizard { public Wizard(String name, int m) { super(name);
_mana = m; }}
46 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Inheritance
Anotherexample:
Inreality,trueinheritanceisrare…
Customer--------------------
name:String
address:Address
-----------------------
validate():boolean
Firm--------------------
name:String
address:Address
firm:String
----------------------
validate():boolean
Customer--------------------
name:String
address:Address
-----------------------
validate():boolean
Firm--------------------
firm:String
47 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Inheritance,reasons
▪ Weuseinheritanceto:
▪ Reusemembers(structural),
e.g.,Customer&Firm
▪ Redefinesomemethods,
e.g.,changethecodeto
validate()
▪ Expresssub-types,e.g.,WizardisaPerson
Customer--------------------
name:String
address:Address
-----------------------
validate():boolean
Firm--------------------
firm:String
48 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Upcasting,downcasting
▪ Upcasting:theabilitytoconsiderareferenceofa
child(sub-class)asifitisareferenceofaparent-
(super-class).
▪ InJavadoneautomatically.
49 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Upcasting,downcasting
▪ Upcasting:theabilitytoconsiderareferenceofa
child(sub-class)asifitisareferenceofaparent-
(super-class).
▪ InJavadoneautomatically.
public static main (String[] args){
Wizard wizard = new Wizard();System.out.println(wizard);
Person person = wizard;System.out.println(person);
}
wizard
Wizard
person
50 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Upcasting,downcasting
▪ Upcasting:theabilitytoconsiderareferenceofa
child(sub-class)asifitisareferenceofaparent-
(super-class).
▪ InJavadoneautomatically.
▪ Note:theobjectisstillaWizard,butwecantreat
itasaPerson(e.g.,additinanArrayList<Person>)
public static main (String[] args){
Wizard wizard = new Wizard();System.out.println(wizard);
Person person = wizard;System.out.println(person);
}
wizard
Wizard
person
51 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Upcasting,downcasting
▪ Downcasting:theabilitytoconsiderareference
toaparent(super-class)asifitisareferenceofto
achild(sub-class)
52 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Upcasting,downcasting
▪ Downcasting:theabilitytoconsiderareference
toaparent(super-class)asifitisareferenceofto
achild(sub-class)
public static main (String[] args){
// assuming I know Zed is a Wizardfor (Person p: persons){
if ( p.getName().equals( "Zed" ) ){Wizard zed = (Wizard)zed;
}}
}
53 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Upcasting,downcasting
▪ Downcasting:theabilitytoconsiderareference
toaparent(super-class)asifitisareferenceofto
achild(sub-class)
▪ Ifyouwanttocheckifanobjectbelongstoaclass
canuseinstanceof if(p instanceof Wizard){…}
public static main (String[] args){
// assuming I know Zed is a Wizardfor (Person p: persons){
if ( p.getName().equals( "Zed" ) ){Wizard zed = (Wizard)zed;
}}
}
54 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
(aside)OOPPolymorphism
▪ Polymorphismistheabilitytotakemanyforms.
InJavaitcanbeseenin:
▪ Objects:becausewecanupcast,anobjectcanbeseenasbeingoftheclassof(oneof)it’sancestors
▪ Methods:becausewecanoverrideamethodthatwe
inherittoadaptitsbehavior
▪ Methods:becausewecanoverloadamethod(i.e.,
haveamethodwithsamenamebutdifferentinput
parameters)toadaptitsimplementationtothe
contextoftheinputparameters
55 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Exercise2–partthreewww.lri.fr/~anab/teaching/remedialJava/ex-class3.pdf
Reminder:
▪ Constructorsarenotinherited
▪ Youcanaccesstheparent’sconstructorwithsuper
▪ Intheconstructor,superneedstobethefirstcommand
56 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Exercise3–Homeworkwww.lri.fr/~anab/teaching/remedialJava/ex-class3.pdf
Reminder:
▪ Constructorsarenotinherited
▪ Youcanaccesstheparent’sconstructorwithsuper
▪ Intheconstructor,superneedstobethefirstcommand
57 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Inheritance
▪ InJavaallclassareinheritingdirectlyorindirectly
fromtheclassjava.lang.Object
▪ Directly:whenwedeclareanewclasswithoutinheritance,thecompileraddsextends Object
▪ Indirectly:whenwedeclareanewclassthatinheritsfromanotherone,theparentclassinherits(directlyor
indirectly)fromtheclassObject
58 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Objectclass
▪ ParentclassofallJavaclasses
▪ Hasbasicmethods(wecanredefine/override)
▪ toString()&hashCode()▪ equals()▪ getClass()▪ clone()▪ finalize()
59 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Equalitytests
▪ Theoperators==and!=test
▪ Valuesforprimitive/basictypes(e.g.,int,double)
▪ ValuesofreferencesforObjects
Point p1;p1=new Point(2,2);Point p2;p2=p1;Point p3;p3=new Point(2,2);p1==p2; //truep1==p3; //falsep2==p3; //false
p1
p2
x:2,y:2
p3 x:2,y:2
60 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
equals()
▪ Thereisamethodequals(Object)inObject
▪ Butgenerallyitsimplementationtestsreferences
(whatisanexceptionwehaveused?)
▪ Tostructurallycomparetwoobjectsweneedto
redefine(override)themethodequals().
Point p1=new Point(2,2);Point p3=new Point(2,2);p1==p3; //falsep1.equals(p3); //false
p1
p2
x:2,y:2
p3 x:2,y:2
61 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
AdvancedInheritance
62 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Canonlyinheritfromoneclass
Canonlyinheritfrom
oneparentclass
(notentirelytrue…)
Person
Wizard Fighter Elf
Wizard
Elf
IfbothWizardandElfimplement(differently)
sayName(),whichonedoesWizardElfcall?
63 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Interfaces(notUI)
Butwhatifthemethod
wasnot
implemented?
Person
Wizard Fighter Elf
Wizard
Elf
64 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
▪ Interfacesdefineatype(asdoclasses)butwithoutcode.Weusethekeywordinterface
▪ Intheinterfaceyoucandeclaremethods
thatsubclasseswillthenhavetoimplement
▪ Wecalltheseabstractmethods
▪ Theyarealwaysdeclaredpublic
Interfaces(notUI)
public interface Elf {public void seeInTheDark(); // simple declaration, no codepublic String otherCoolStuffICanDo ( int coolness );
}
65 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Interfaces
Thenweneedtodefineaclass
thatinheritsthedeclarations
oftheabstractmethodsin
theinterface,andprovides
codeforthem
Weusethekeyword
implements
Person
Wizard Fighter Elf
Wizard
Elf
66 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Interfaceimplementation
public interface Elf {public void seeInTheDark(); // simple declaration, no codepublic String otherCoolStuffICanDo ( int coolness );
}
public class WizardElf extends Wizard implements Elf{
public void seeInTheDark(){System.out.println("I see as well as a cat" );
}
public String otherCoolStuffICanDo ( int coolness ){if ( coolness < 5 )
System.out.println("Not so cool after all" ); }
}
67 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
▪ Aninterfacehasnocode(i.e.,isnotimplemented)
andsocannotbeinstantiated(i.e.,wecannot
createobjectsoftheirtypeusingnew)
▪ Thecompilerverifiesthatonceaclassimplements
aninterface,itimplementsallitsmethods
▪ Aclasscanimplementmorethanoneinterfaces,
andthusinheritstheircombineddeclarations
▪ ThisistheclosestJavacomestomultipleinheritance
Interfaces
68 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Interfaces
public interface Elf {public void seeInTheDark(); // simple declaration, no code
}public interface Running {
public int run( int time ); // simple declaration, no code}
public class WizardElf extends Wizard implements Elf, Running{private int _distance = 0;
@Overridepublic void seeInTheDark(){ // inherited from Elf
System.out.println("I see as well as a cat" );}@Overridepublic int run ( int time ){// inherited from Running
_distance += time*10;}
}
69 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
▪ Inheritfromaclass:
▪ Thesubclassisatypeoftheparentclass
▪ Implementaninterface:
▪ Enforcetheimplementationofspecificmethods(i.e.,
sharedfunctionality)
▪ Objectsthatsharedifferentgroupsoffunctionalities
(acalltointerfacemethodsisabitslower)
InterfaceorClassInheritance
70 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Exercise5www.lri.fr/~anab/teaching/remedialJava/ex-class3.pdf
Reminder:
▪ Interfacecreation:public interface INTERFACENAME{}
▪ Interfaceonlyhas(abstract)methoddeclarations,allpublic
▪ Aclassimplementsoneormoreinterfaces
class CLASSNAME implements INTERFACENAME{}
▪ Aclassthatimplementsaninterfaceneedstoprovidecodeforalltheabstractmethodsdefinedintheinterface(thekeyword
@Overrideproceedstheircode)
71 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
▪ ItispossibletocreateinJavaclasseswithabstract
methods,i.e.,methodsthatchildclassesneedto
implement
▪ Abstractclassescanalsohavefieldsandmethodswith
implementationaswell,soitisapartiallyimplemented
class
▪ Theycaninheritnormallyfromotherclassesor
implementinterfaces
▪ BUTtheycannothaveinstances(i.e.,wecannot
createanobjectfromthemusingnew)
Abstractclasses
72 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Abstractclassespublic interface Moving {
public int run( int time ); public int walk( int time );
}public interface Resting {
public void stand( int time ); public void sleep( int time );
}
public abstract class Person implements Moving,Resting {String _name;int _distance;public int run( int time ){
distance += time*10; // implemented method}public abstract void sayName(); // declaration only
}
// What code does Wizard have to provide?public class Wizard extends Person {}
73 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
TypeandClass:reminder
public static void main (String args[]){String s = args[0];Car k = new Car (“peugeot”, “pink”);
}
Asidenote:
▪ VariableshaveaType▪ ReferenceshaveaClass
Type Class
74 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
TypeandClass:reminder
public static void main (String args[]){String s = args[0];Car k = new Car (“peugeot”, “pink”);
}
Asidenote:
▪ VariableshaveaType▪ ReferenceshaveaClass
Type Class
75 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Typesvsclasses
▪Whichofthefollowingarecorrect?
public interface Moving { … }public interface Resting {… }public abstract class Person implements Moving,Resting {…}public class Wizard extends Person { … }public class Fighter extends Person { … }
Person p = new Person("John");Wizard z = new Wizard("Zed");Fighter f = new Fighter("Fred");Resting r = new Resting("Resting");Person p2 = z;
ArrayList<Person> people = new ArrayList<Person>();people.add(z);people.add(f);for (Person ip: people){
if (ip instanceof Wizard) {…}}
76 ABezerianos - Remedial Java - Session-3.key - 6 September 2019
Objectcollections:ArrayLists
(Aside)
▪ ArrayListsareonetypeofList(thatisan
interface).Oftenitisbesttodeclarethetypeas
Listandinstantiate(i.e.,implement)using
ArrayList.
▪ Thiscanmakeeasierinthefuturetochangethe
implementationofyourList(touseforexample
LinkedList)
(seeJavaAPIoncollectionsformoreinfo)
77 ABezerianos - Remedial Java - Session-3.key - 6 September 2019