600 likes | 617 Views
Learn about inheritance, upcasting and downcasting, instanceof operator, abstract classes and methods, and Java interfaces.
E N D
Week 9 More inheritance, Abstract Classesand Interfaces
LectureOutline • Inheritance • Upcasting anddowncasting • instanceof • Abstract class andmethods • JavaInterface • final keyword inJava
Upcasting anddowncasting • Upcasting Java supports an object of a subclass type to be treated as an object ofany superclass type. It is doneautomatically. • Downcasting It is tobe performed manually by thedevelopers.
Upcasting and downcastingcontd. Upcasting Object implicit Animal Cat Bird Downcasting
Upcasting and downcastingcontd. • Upcasting and downcasting are NOT like casting primitive datatypes from one toother • By casting we are not actually changing the object itself, you are just labelling itdifferently
Upcasting and downcastingcontd. Upcasting Object implicit Animal Cat Bird Catis-aAnimal√ Animalis-aCatX Animal is-a BirdX Downcasting Birdis-aAnimal√
Upcasting and downcastingcontd. public class Animal { String name; Animal(){} Animal(Stringname){ this.name =name; } public voidsound() { System.out.println("No sound!"); } }
Upcasting and downcastingcontd. classCat extends Animal { Cat(Stringname) { super(name); } public void sound() { System.out.println(name+"Meowing!"); } }
Upcasting and downcastingcontd. classBirdextends Animal { Bird(Stringname) { super(name); } public void sound() { System.out.println(name+"Tweeting!"); } }
Upcasting and downcastingcontd. classTestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animalanimal animal.sound(); } = newAnimal(); Output:? }
Upcasting and downcastingcontd. classTestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animalanimal animal.sound(); } = newAnimal(); Output: Bela Meowing! HappyTweeting! Nosound! }
Upcastingexample classTestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = newBird("Happy"); bird.sound(); Animalanimal = new Animal(); animal = cat; //automatic upcasting animal.sound(); } }
Upcastingexample classTestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = newBird("Happy"); bird.sound(); Animalanimal = newAnimal(); animal = cat; //automatic upcasting animal.sound(); Output: } Bela Meowing! HappyTweeting! Bela Meowing! }
Downcastingexample class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animalanimal = new Animal(); animal = cat; //automaticupcasting Cat cat2 = (Cat) animal;//downcasting manually cat2.sound(); } Output: Bela Meowing! HappyTweeting! Bela Meowing! }
Observation(1) class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animalanimal = newAnimal(); animal = cat; //automaticupcasting Bird bird2 = (Bird) animal;//downcasting?? bird2.sound(); } Output:?? }
Observation(2) • As in the Hierarchy we can have many different Animals,andifwewanttodowncastthemallto Cat, whathappens? • For example, Cat toBird • But Cat is definitely not-aBird Exception in thread "main"java.lang.ClassCastException: OOSD1.Cat cannot be cast toOOSD1.Bird This is because of Dynamic binding (although code willcompile)
instanceof class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animalanimal = new Animal(); animal = cat; //automatic upcasting if(animal instanceofCat){ Cat cat2 = (Cat) animal;//downcasting } cat2.sound(); } }
Observation(3) class TestAnimal { public static void main(String[] args) { Cat cat=new Animal(); } } Incompatibletypes: Shape cannot be converted toSquare
How classes aredesigned • Super classes are created through the processcalled • "generalization" • Common features (methods/variables) are factored outof objectclassifications • Those features are formalized in aclass • This becomes thesuperclass • The classes from which the common features weretaken become subclasses to the newly created superclass
How classes are designedcontd. • Often, the superclass does not have a "meaning" or doesnotdirectlyrelatetoa"thing"intherealworld • It is an artefact of thegeneralization process • Because of this, abstract classes cannotbe instantiated • They act as place holders forabstraction
Abstract baseclass named inItalic Example • In this example, the subclasses represent objects (classes)taken from the problemdomain. • The superclass represents an abstract concept that does notexist "as is" in the realworld.
Observation In the following, doesn’t seem like we have enoughinformationtogetthesound()ifallwe know is it is anAnimal. public class Animal { String name; Animal(){} Animal(Stringname){ this.name =name; } public voidsound() { System.out.println("Nosound!"); } }
PotentialSolutions Just leave it for thesub classes. – Have each sub class definesound() Define sound() in Animal as in the previousslide Sub classes override the method with moremeaningful behavior as in the lastexample.
A bettersolution • Weknowwewanttobeabletofindthe soundofobjectsthatare • instances ofAnimal • Theproblemiswedon’tknowhowtodothatifallweknowisitsan Animal • Make sound() an abstract method-JavaKeyword • public class Animal { String name; Animal(){} Animal(Stringname){ • this.name =name; • } • public abstract voidsound(); • }
Abstractmethod public class Animal { String name; Animal(){} Animal(Stringname){ this.name = name; } public abstract voidsound(); // We know we want it, but don’t know how,yet… }
Abstractmethod • Methods that are declared abstract have no body anundefined behavior. • We can override this sound() method in the Cat andSquare subclasses, and implementdetails
Abstract methodcontd. class Cat extends Animal { Cat(Stringname) { super(name); } public void sound() { System.out.println(name+"Meowing!"); } } Now we know how to define thesound()
Abstract methodcontd. class Bird extends Animal { Bird(Stringname) { super(name); } public void sound() { System.out.println(name+"Tweeting!"); } } Now we know how to define thesound()
Abstract methodcontd. • sound()is now an abstract method in Animal • what is wrong with the followingcode? • Animal animal = new Animal(); System.out.println(animal.sound());
Abstract methodcontd. • sound()is now an abstract method in Animal • what is wrong with the followingcode? • Animal animal = new Animal(); System.out.println(animal.sound()); • Undefined behavior!BAD
Abstractclass • Not good to have undefinedbehaviors • If a class has ONE or more abstract methods, the class must also be declaredabstract. • abstract class Animal { String name; Animal(){} Animal(Stringname){ • this.name =name; • } • public abstract voidsound(); • }
Abstractclass • abstract class Animal { String name; Animal(){} Animal(Stringname){ • this.name =name; • } • public abstract voidsound(); • } • what is wrong withthe following code? • Animal animal = newAnimal();
Abstractclass • abstract class Animal { String name; Animal(){} Animal(Stringname){ • this.name = name; • } • public abstract voidsound(); • } • what is wrong withthe following code? • Animal animal = newAnimal(); • //Syntaxerror • If a class is abstract, then we cannot createinstances • of thatclass
What is an abstractclass? • An abstract class is a class that isdeclared • abstract. • Important: Even if a class has zero abstract methods a programmer can still choose to make itabstract • Abstract classes cannot be instantiated,but they can be subclassed.
Abstract class example public abstract class Animal { Stringname; Animal(){} Animal(Stringname){ this.name =name; } public abstract voidsound(); }
Abstract class examplecontd. classCat extends Animal { Cat(Stringname) { super(name); } public void sound() { System.out.println(name+"Meowing!"); } }
Abstract class examplecontd. classBirdextends Animal { Bird(Stringname) { super(name); } public void sound() { System.out.println(name+"Tweeting!"); } }
Abstract class examplecontd. classTestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); //Animalanimal = newAnimal(); //animal.sound(); } } Output: BelaMeowing! HappyTweeting!
Abstract classproperties • Abstract classes may or may not contain abstractmethods • If a class contains at least one abstract method, thenthe class must be declaredabstract • If a class is declared abstract, it cannotbe instantiated • To use an abstract class, you have to inherit it fromanother • class,provideimplementationstotheabstractmethodsinit. • If you inherit an abstract class, you have toprovide • implementationstoalltheabstractmethodsinit.
Abstract class propertiescontd. • Ifyoudon’timplementanabstractmethod(declaredinthe abstractclass)inthesub-class,thenwhatwillhappen? • public abstract class Animal{ Stringname; • Animal(){} Animal(String name){ this.name =name; • } • public abstract voidsound(); • } • class Cat extends Animal { Cat (Stringname) { super(name); • }
Abstract class propertiescontd. • Ifyoudon’timplementanabstractmethod(declaredinthe abstractclass)inthesub-class,thenwhatwillhappen? • class TestAnimal{ • public static void main(String[]args) • { • Cat cat = newCat("Bela"); • }
Abstract class propertiescontd. • Ifyoudon’timplementanabstractmethod(declaredinthe abstractclass)inthesub-class,thenwhatwillhappen? • class TestAnimal{ • public static void main(String[]args) • { • Cat cat = new Cat("Bela");//Error • }
Week 10 Java Interfaces
Learning Outcomes • At the end of this session, You will able to: • Understand Java Interface; • To Analyse how Interfaces and different then Abstract classes; • Design and Implement Interfaces and Abstracts.
LectureOutline • JavaInterface • Interface vs Abstract • final keyword inJava
What is anInterface? • A Java Interface is just a definition of behaviour, similar toa • Java abstract class (we will see their differencesshortly) • Itisnotaclassbutitisdefinedina waysimilartotheclass definition • An Interface describes the functions and behaviors ofa specific object type butdoesn't implement them • When a class implements an interface it has toimplement all methods declared in thatinterface.
Java InterfaceExample InterfaceAnimal // interface declaration public interface Animal{ // constant public static final String type ="Mammal"; //abstract method public void sound(); }
Java InterfaceExample Cat implements InterfaceAnimal class Cat implements Animal { private Stringname; Cat (String name) { this.name =name; } // classdeclaration public void sound (){ System.out.println(name+"Meowing!"); } }