Foundations of Programming 2: Abstract Classes and Interfaces

Slides:



Advertisements
Similar presentations
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Advertisements

Sadegh Aliakbary Sharif University of Technology Fall 2010.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Abstract Classes and Interfaces
Multiple Choice Solutions True/False a c b e d   T F.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Object Oriented Programming: Java Edition By: Samuel Robinson.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Chapter 6 Interfaces. Class Status CU will be close for winter break from Dec. 22. till Jan.2 We have 3 classes left after tonight (Jan 8,15, and 22)
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Interfaces and Polymorphism CS 162 (Summer 2009).
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Lecture 5:Interfaces and Abstract Classes
Using the Java Collection Libraries COMP 103 # T2
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Advanced Programming in Java
Advanced Programming in Java
Sixth Lecture ArrayList Abstract Class and Interface
Sections Inheritance and Abstract Classes
Lecture 12 Inheritance.
Abstract Classes and Interfaces
Inheritance and Polymorphism
03/10/14 Inheritance-2.
IST311 / 602 Cleveland State University – Prof. Victor Matos
Exceptions, Interfaces & Generics
Chapter 3: Using Methods, Classes, and Objects
OOP’S Concepts in C#.Net
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
More inheritance, Abstract Classes and Interfaces
Interface.
Interfaces.
Advanced Programming Behnam Hatami Fall 2017.
CS18000: Problem Solving and Object-Oriented Programming
Generics.
Advanced Programming in Java
Inheritance Inheritance is a fundamental Object Oriented concept
Java Inheritance.
Advanced Programming in Java
CMSC 202 Generics.
Fundaments of Game Design
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
IST311 / 602 Cleveland State University – Prof. Victor Matos
Review of Previous Lesson
Chapter 8 Inheritance Part 2.
Abstract Classes and Interfaces
Agenda Inheritance Polymorphism Type compatibility Homework.
CMPE212 – Reminders Assignment 2 due next Friday.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Dasar-Dasar Pemrograman 2: Generics
Topics OOP Review Inheritance Review Abstract Classes
Dasar-Dasar Pemrograman 2: Java Conditions and Loops
Foundations of Programming 2: Inheritance and Polymorphism
Foundations of Programming 2: JavaFX Basics
CS 240 – Advanced Programming Concepts
Presentation transcript:

Foundations of Programming 2: Abstract Classes and Interfaces FoP 2 Teaching Team, Faculty of Computer Science, Universitas Indonesia Correspondence: Fariz Darari (fariz@cs.ui.ac.id) https://www.pexels.com/photo/multicolored-abstract-art-2062637/ Feel free to use, reuse, and share this work: the more we share, the more we have!

Not everything is concrete, some are abstract, but why, because they are meant to be like that. https://unsplash.com/photos/KMn4VEeEPR8

Why?

Why? Does it really make sense to make an object of the class Vehicle? I mean, how could you have a vehicle without knowing if it's a car, a truck, or a motorcycle?

Abstract class: Rules An abstract class is abstract, in the sense that you cannot concretize it (that is, you cannot instantiate any object). However (and this is the reason abstract classes can be useful) , you can create a class extending an abstract class. An abstract class may have abstract methods (beside the standard ones), while an abstract method must be in an abstract class. A class extending an abstract class must implement all the abstract methods.

Abstract method An abstract method is abstract, in the sense that it is not implemented, like this: abstract void hello(String name);

Quiz time: Guess the output (not here, later) public abstract class SimpleAbstract { int x; // an abstract class can have a constructor SimpleAbstract() { System.out.println("Abstract"); } abstract void hello(String name); // abstract method // an abstract class can have a standard method void concrete() { System.out.println("Concrete in abstract");

Quiz time: Now guess the output public class Simple extends SimpleAbstract { // try to comment this void hello(String name) { System.out.println("Hello, " + name); } public static void main(String[] args) { // try to uncomment this // SimpleAbstract sa = new SimpleAbstract(); // guess output Simple s = new Simple(); s.hello("Sis"); System.out.println(s.x); s.concrete();

Quiz time: Now try to implement this. abstract Fields: color and price Abstract: drive(), stop(), zigzag() Nonabstract: horn() printing "Beep!" Create a main class instantiating all the nonabstract classes. Inspired from: https://blog.eduonix.com/java-programming-2/learn-about-abstract-classes-in-java/ non-abstract non-abstract non-abstract

Quiz time: Now try to implement this. Animal abstract Abstract: makeSound() Cat Dog Bird Note that it's odd to create an instance of Animal. Can you imagine how it looks like? Perhaps a lump of meat with legs? non-abstract non-abstract non-abstract

Quiz time: Difference between nonabstract and abstract classes? - Nonabstract classes can be instantiated, while abstract cannot. - Nonabstract classes cannot enforce subclasses to implement (abstract) methods, while abstract can.

Quiz time: Difference between nonabstract and abstract classes? - Nonabstract classes can be instantiated, while abstract cannot. - Nonabstract classes cannot enforce subclasses to implement (abstract) methods, while abstract can. - Nonabstract classes can be instantiated, while abstract cannot. - Nonabstract classes cannot enforce subclasses to implement (abstract) methods, while abstract can.

https://unsplash.com/photos/OIRoFbbQa3E Spiky = interface Interfaces

Interfaces Interfaces define a contract: What a class can do, but (generally) not the how As opposed to (abstract) classes, a class may "extends" multiple interfaces. Well, it is now called "implements", not "extends". Methods in interfaces are implicitly abstract and public. Interfaces cannot have constructors. Interfaces are like features, for example, you can add features to your smartphone, like GPS-featured and radio-featured. Similarly, Rentable could be an interface for Car, and Book; and Edible could be an interface for Mushroom, and Chicken. Observe that the classes implementing an inteface could be totally different.

Interfaces for Cellphone public interface GPSEnabled { // put in separate source code public void printLocation(); } public interface RadioEnabled { // put in separate source code public void startRadio(); public void stopRadio(); // put in separate source code public class Cellphone implements GPSEnabled, RadioEnabled { public void printLocation() { System.out.println("Location"); public void startRadio() { System.out.println("Radio is ON!"); public void stopRadio() { System.out.println("Radio is OFF!"); } } Inspired from: https://guide.freecodecamp.org/java/interfaces

Quiz time: What is the output? // .. put inside Cellphone.java public static void main(String[] args) { Cellphone ciaoMi = new Cellphone(); ciaoMi.printLocation(); ciaoMi.startRadio(); GPSEnabled samsu = new Cellphone(); samsu.printLocation(); samsu.startRadio(); } Inspired from: https://guide.freecodecamp.org/java/interfaces

Quiz time Create an interface of AIEnabled The interface should include the following methods: turnonChatbot(): turn on chatbot module turnoffChatbot(): turn off chatbot module checkChatbot(): check if chatbot module is on Implement AIEnabled in Cellphone Test your code

Solution: AIEnabled.java public interface AIEnabled { // turn on chatbot module void turnonChatbot(); // turn off chatbot module void turnoffChatbot(); // check if chatbot module is on boolean checkChatbot(); }

Solution: Cellphone.java public class Cellphone implements AIEnabled { // ... boolean chatbotModule = false; public void turnonChatbot() { chatbotModule = true; } public void turnoffChatbot() { chatbotModule = false; } public boolean checkChatbot() { return chatbotModule; } } AIEnabled ciaoMi = new Cellphone(); System.out.println(ciaoMi.checkChatbot()); ciaoMi.turnonChatbot(); ciaoMi.turnoffChatbot();

Quiz time: List, ArrayList, and LinkedList public static void main(String[] args) { List<String> lst1 = new ArrayList<String>(); lst1.add("A");lst1.add("B");lst1.add("C"); System.out.println(lst1.contains("A")); ((ArrayList<String>) lst1).ensureCapacity(100); System.out.println(lst1); List<String> lst2 = new LinkedList<String>(); lst2.add("A");lst2.add("B");lst2.add("C"); ((LinkedList<String>) lst2).addFirst("9"); System.out.println(lst2); } List = interface ArrayList and LinkedList = class List has methods: add and contains ArrayList has methods: ensureCapacity (increases the capacity of this ArrayList instance) LinkedList has methods: addFirst (inserts the specified element at the beginning of this list) What can you observe? Both AL and LL are lists, but implemented differently: https://dzone.com/storage/temp/895349-arraylist-linkedlistt.png

Quiz time: List, ArrayList, and LinkedList public static void main(String[] args) { List<String> lst1 = new ArrayList<String>(); lst1.add("A");lst1.add("B");lst1.add("C"); System.out.println(lst1.contains("A")); ((ArrayList<String>) lst1).ensureCapacity(100); System.out.println(lst1); List<String> lst2 = new LinkedList<String>(); lst2.add("A");lst2.add("B");lst2.add("C"); ((LinkedList<String>) lst2).addFirst("9"); System.out.println(lst2); } Yes, check Javadoc Any other methods that exist in LinkedList only? Both AL and LL are lists, but implemented differently: https://dzone.com/storage/temp/895349-arraylist-linkedlistt.png

Quiz time: List, ArrayList, and LinkedList public static void main(String[] args) { List<String> lst1 = new ArrayList<String>(); lst1.add("A");lst1.add("B");lst1.add("C"); System.out.println(lst1.contains("A")); ((ArrayList<String>) lst1).ensureCapacity(100); System.out.println(lst1); List<String> lst2 = new LinkedList<String>(); lst2.add("A");lst2.add("B");lst2.add("C"); ((LinkedList<String>) lst2).addFirst("9"); System.out.println(lst2); } Stack Any other classes implementing List? Both AL and LL are lists, but implemented differently: https://dzone.com/storage/temp/895349-arraylist-linkedlistt.png

A tour to source code of: List, ArrayList, and LinkedList http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/List.java http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/ArrayList.java http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/LinkedList.java

Don't do this! public interface GPSEnabled { public void printLocation(); } public interface RadioEnabled { public int printLocation(); public void startRadio(); public void stopRadio(); public class Cellphone implements GPSEnabled, RadioEnabled { public void printLocation() { // return location // ... What's wrong? Overlapped methods with different return types!

Don't do this! What's wrong? public interface GPSEnabled { public void printLocation(); } public interface RadioEnabled { public int printLocation(); public void startRadio(); public void stopRadio(); public class Cellphone implements GPSEnabled, RadioEnabled { public void printLocation() { // return location // ... What's wrong? Overlapped methods with different return types! What's wrong? Name collision: Overlapped methods with different return types!

It's possible for an interface to extend interfaces interface A { .. } interface B { .. } interface C extends A, B { .. }

Interfaces for Cellphone: Say, you want to add a new method for interface RadioEnabled public interface RadioEnabled { public void startRadio(); public void stopRadio(); } public class Cellphone implements RadioEnabled { public void startRadio() { // start radio public void stopRadio() { // stop radio

Interfaces for Cellphone: Say, you want to add a new method for interface RadioEnabled public interface RadioEnabled { public void startRadio(); public void stopRadio(); public void recordRadio(); } public class Cellphone implements RadioEnabled { public void startRadio() { // start radio public void stopRadio() { // stop radio Unresolved compilation problem What might happen?

Interfaces for Cellphone: Say, you want to add a new method for interface RadioEnabled public interface RadioEnabled { public void startRadio(); public void stopRadio(); default public void recordRadio() { System.out.println("Recording radio.."); } public class Cellphone implements RadioEnabled { public void startRadio() { // start radio public void stopRadio() { // stop radio We can have a default implementation of a method in an interface (Java 8+)

Interfaces for Cellphone: Say, you want to add a new method for interface RadioEnabled public interface RadioEnabled { public void startRadio(); public void stopRadio(); default public void recordRadio() { System.out.println("Recording radio.."); } public class Cellphone implements RadioEnabled { public void startRadio() { // start radio public void stopRadio() { // stop radio You can still override the default methods. We can have a default implementation of a method in an interface (Java 8+) So the new method won't break your existing code!

Quiz time: Have a look at Comparable interface in JavaDoc, and try to create an Employee class implementing the Comparable interface, such that employees can be compared based on the order of their instantiations (employees created first get more priorities than those created later). From your implementation, demonstrate how you can sort an Employee list, based on the employee instantiation order. Tips: Have a look at JavaDoc

Picture: https://unsplash.com/photos/VyC0YSFRDTU Inspired by: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html Liang. Introduction to Java Programming. Tenth Edition. Pearson 2015. Think Java book by Allen Downey and Chris Mayfield. Eck. Introduction to Programming Using Java. 2014.