1 / 60

Week 9 More inheritance, Abstract Classes and Interfaces

Learn about inheritance, upcasting and downcasting, instanceof operator, abstract classes and methods, and Java interfaces.

misaacs
Download Presentation

Week 9 More inheritance, Abstract Classes and Interfaces

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 9 More inheritance, Abstract Classesand Interfaces

  2. LectureOutline • Inheritance • Upcasting anddowncasting • instanceof • Abstract class andmethods • JavaInterface • final keyword inJava

  3. 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.

  4. Upcasting and downcastingcontd. Upcasting Object implicit Animal Cat Bird Downcasting

  5. 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

  6. Upcasting and downcastingcontd. Upcasting Object implicit Animal Cat Bird Catis-aAnimal√ Animalis-aCatX Animal is-a BirdX Downcasting Birdis-aAnimal√

  7. Upcasting and downcastingcontd.

  8. Upcasting and downcastingcontd. public class Animal { String name; Animal(){} Animal(Stringname){ this.name =name; } public voidsound() { System.out.println("No sound!"); } }

  9. Upcasting and downcastingcontd. classCat extends Animal { Cat(Stringname) { super(name); } public void sound() { System.out.println(name+"Meowing!"); } }

  10. Upcasting and downcastingcontd. classBirdextends Animal { Bird(Stringname) { super(name); } public void sound() { System.out.println(name+"Tweeting!"); } }

  11. 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:? }

  12. 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! }

  13. 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(); } }

  14. 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! }

  15. 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! }

  16. 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:?? }

  17. 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)

  18. 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(); } }

  19. Observation(3) class TestAnimal { public static void main(String[] args) { Cat cat=new Animal(); } } Incompatibletypes: Shape cannot be converted toSquare

  20. Abstractclass

  21. 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

  22. 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

  23. 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.

  24. 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!"); } }

  25. 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.

  26. 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(); • }

  27. 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… }

  28. Abstractmethod • Methods that are declared abstract have no body anundefined behavior. • We can override this sound() method in the Cat andSquare subclasses, and implementdetails

  29. 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()

  30. 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()

  31. 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());

  32. 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

  33. 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(); • }

  34. Abstractclass • abstract class Animal { String name; Animal(){} Animal(Stringname){ • this.name =name; • } • public abstract voidsound(); • } • what is wrong withthe following code? • Animal animal = newAnimal();

  35. 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

  36. 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.

  37. Abstract class example public abstract class Animal { Stringname; Animal(){} Animal(Stringname){ this.name =name; } public abstract voidsound(); }

  38. Abstract class examplecontd. classCat extends Animal { Cat(Stringname) { super(name); } public void sound() { System.out.println(name+"Meowing!"); } }

  39. Abstract class examplecontd. classBirdextends Animal { Bird(Stringname) { super(name); } public void sound() { System.out.println(name+"Tweeting!"); } }

  40. 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!

  41. 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.

  42. 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); • }

  43. Abstract class propertiescontd. • Ifyoudon’timplementanabstractmethod(declaredinthe abstractclass)inthesub-class,thenwhatwillhappen? • class TestAnimal{ • public static void main(String[]args) • { • Cat cat = newCat("Bela"); • }

  44. Abstract class propertiescontd. • Ifyoudon’timplementanabstractmethod(declaredinthe abstractclass)inthesub-class,thenwhatwillhappen? • class TestAnimal{ • public static void main(String[]args) • { • Cat cat = new Cat("Bela");//Error • }

  45. Week 10 Java Interfaces

  46. 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.

  47. LectureOutline • JavaInterface • Interface vs Abstract • final keyword inJava

  48. 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.

  49. Java InterfaceExample InterfaceAnimal // interface declaration public interface Animal{ // constant public static final String type ="Mammal"; //abstract method public void sound(); }

  50. 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!"); } }

More Related