Abstract Classes and Interfaces Lecture 2 – 9/6/2012.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming with Java
Abstract Classes & Interfaces Definitions –abstract methods = Methods that are declared, with no implementation –abstract class = A class with abstract.
Interfaces A Java interface is a collection
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.
9. Inheritance 9.1 Subclasses 9.2 Polymorphism 9.3 Abstract Classes 9.4 Modifiers and Access 9.6 Object-Oriented Design with Use Cases and Scenarios.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Object-Oriented PHP (1)
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,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Chapter 10 Classes Continued
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
Abstract Classes b b An abstract class is a placeholder in a class hierarchy that represents a generic concept b b An abstract class cannot be instantiated.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Inheritance using Java
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Polymorphi sm. 2 Abstract Classes Java allows abstract classes – use the modifier abstract on a class header to declare an abstract class abstract class.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Peyman Dodangeh Sharif University of Technology Fall 2014.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Java Software Solutions Lewis and Loftus Chapter 9 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Enhanced Class Design -- Introduction.
Coming up: Inheritance
JAVA Programming (Session 4) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Chapter 5: Enhancing Classes
Chapter 15 Abstract Classes and Interfaces
Inheritance and Polymorphism
Chapter 13 Abstract Classes and Interfaces
Class Inheritance (Cont.)
Advanced Programming Behnam Hatami Fall 2017.
Programming in C# CHAPTER - 11
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Advanced Java Programming
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chapter 14 Abstract Classes and Interfaces
Final and Abstract Classes
Presentation transcript:

Abstract Classes and Interfaces Lecture 2 – 9/6/2012

Objectives  Review OOP Concepts  Static variables and methods  Scope of variables and methods  Abstract classes  Interfaces  Comparing Abstract class and Interfaces 2

Object Oriented Programming (OOP) 3  OOP Is a programming paradigm using objects.  Why OOP? We usually think about real world objects, such as a desk, car, student, etc.  Each object has a unique identity, state, and behavior:  The state is represented as data fields (class member variables).  The behavior of an object is defined by a set of methods.

Features of OOP 4  PIE  Polymorphism  Polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning to a particular symbol or "operator" in different contexts.  Difficult to describe, easier to show, so we’ll look at examples later.  Inheritance  Encapsulation

Features of OOP 5  PIE  Polymorphism  Inheritance  Inheritance is the ability to define a new class in terms of an existing class  The existing class is the parent, base or superclass  The new class is the child, derived or subclass  The child class inherits all of the attributes and behaviour of its parent class  It can then add new attributes or behaviour  Or even alter the implementation of existing behaviour (methods)  Avoids defining data fields and methods for a subclass that are may be generic for a set of classes.  This not only speeds up program development; it also ensures an inherent validity to the defined subclass object.  Encapsulation

Features of OOP 6  PIE  Polymorphism  Inheritance  Encapsulation  The data (state) of an object is private – it cannot be accessed directly. The state can only be changed through its behaviour, otherwise known as its public interface.  The object is said to publish its interfaces. Other objects adhere to these interfaces to use the object without having to be concerned with how the object accomplishes it.  The idea is "don't tell me how you do it; just do it." An object can be thought of as a self-contained atom. The object interface consists of public methods and instantiate data.

Inheritance 7  A subclass has an ‘is a’ relationship to the parent class.  Subclasses absorb the attributes (data fields) and behaviors (methods) of the parent class and extend these capabilities.  Benefits:  Extensibility: New functionality may be easily plugged in without changing existing classes.  Reusability: Reuse core set of data fields and methods and extended by classes that fill in the application-dependent part.

Inheritance vs. Composition 8  Inheritance implements ‘is a’ relationship.  Subclass uses the ‘extends’ keyword to inherit the attributes and methods of parent class.  Ex. A Square is a Shape  Composition implements ‘has a’ relationship  A class has objects of other classes as members  Ex. An Employee has a BirthDate  Ex. A Square has a Point

Composition Example 9

Inheritance Example 10

Visibility Modifiers  Java has 4 visibility modifiers  Public  Default  Private  Protected  Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers. 11

Class level access modifiers (java classes only) 12  Only two access modifiers is allowed, public and no modifier (called default)  If class is decalred public, then it CAN be accessed from ANYWHERE.  If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

Member level access modifiers (java variables and java methods) 13  All the 4 public, private, protected and no modifier is allowed.  public  Can be accessed from anywhere  no modifier (default)  Can be accessed from the same class or package  private  Can be accessed from the same class only  protected  Can be accessed from the same package  Can be accessed from a subclass existing in any package

Visibility Modifiers 14 Access Modifiers Same ClassSame PackageSubclass Other packages publicYYYY protectedYYYN no access modifier YYNN privateYNNN

Instance Variables  The data field ‘radius’ in the circle class is called an instance variable.  Instance variables are tied to a specific instance of the class (not shared among objects of the same class). class Circle { int radius; // instance variable public Circle(int r) { radius = r; } public int getRadius() { return radius; } Ex. Circle c1 = new Circle(5); Circle c2 = new Circle(8); System.out.println(c1.getRadius()); // 5 System.out.println(c2.getRadius()); // 8 Objects c1 and c2 have their own copy of instance variable ‘radius.’ 15

Static Variables  Static variables (also called class variables) are shared among class objects.  Ex. We will add a static variable ‘count’ to count the number of circle objects created. class Circle { int radius; // instance variable static int count = 6; public Circle(int r) { radius = r; count ++; } public void printCount() { System.out.println(count); } Circle c1 = new Circle(5); c1.printCount(); // 1 Circle c2 = new Circle(8); c1.printCount(); // 2 c2.printCount(); // 2 Circle c3 = new Circle(10); c1.printCount(); // 3 c2.printCount(); // 3 c3.printCount(); // 3 All object of class ‘Circle’ share 1 copy of static variable ‘count’. 16

Static Methods  Methods that operate on static variables are declared static class Circle { int radius; // instance variable static int count = 6; // static variable public Circle(int r) { radius = r; count ++; } public static void printCount() { System.out.println(count); } 17 Method declared static

Static Methods  Static methods can be called without creating an instance of a class.  Why? Cause they only operate on static variables. 18 Circle c1; Circle.printCount(); // 0 Circle c2 = new Circle(8); c2.printCount(); // 1 class Circle { int radius; // instance variable static int count = 0; // static variable public Circle(int r) { radius = r; count += 1; } public static void printCount() { System.out.println(count); } Its recommended that you invoke static variables and methods using ClassName.variable and ClassName.method.

Motivation for Abstract Classes  Moving up the inheritance chain (from sub-class to super- class) the classes become more general and describe general/common features. Shape RectangleCircle getArea(); getPerimeter(); getPerimeter() and getCircle() are common features of geometric objects getArea(); getPerimeter(); getRadius(); getArea(); getPerimeter(); getWidth(); getHieght(); 19

Abstract Classes  An abstract class usually has one method defined as abstract.  An abstract method is a method that has only its signature defined without its body. 20 public abstract class Vehicle { String name; public String getName() { return name; \\ method body } public abstract void move(); \\ no body! }

Abstract Classes  Abstract class (like regular classes) have data fields and methods.  Unlike regular classes, cannot create an instance of an abstract class using the new operator.  An abstract method is a method signature without implementation.  Any (non-abstract) sub-class of an abstract class, must provide the implementation of an abstract method.  The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate. 21

22 Java Interface  A Java interface is a class-like construct that contains constants and abstract methods  since all methods in an interface are abstract, the abstract modifier is usually left off  Methods in an interface have public visibility by default  As with abstract classes, cannot create an instance of a interface with the new operator

23 Interface: Syntax public interface Doable { public static final String NAME; public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word No method in an interface has a definition (body)

24 Implementing an Interface  A class formally implements an interface by  stating so in the class header in the implements clause  a class can implement multiple interfaces: the interfaces are listed in the implements clause, separated by commas  If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors

25 Implementing Interfaces public class Something implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition public class ManyThings implements Doable, AnotherDoable

26 Polymorphism via Interfaces  Define a polymorphism reference through interface  declare a reference variable of an interface type Comparable obj;  the obj reference can be used to point to any object of any class that implements the Comparable interface  the version of compareTo depends on the type of object that obj is referring to: obj.compareTo();

27 Interface Hierarchies  Inheritance can be applied to interfaces as well as classes  One interface can be used as the parent of another  The child interface inherits all methods of the parent  A class implementing the child interface must define all methods from both the parent and child interfaces

Interfaces vs. Abstract Classes variablesconstructorsmethods AbstractNo restrictionConstructors are invoked by subclasses. Cannot be instantiated using new operator At least one method must be abstract InterfaceAll variables must be public static final No const Cannot be instantiated using new operator Constructor All methods must be public abstract 28

Interfaces vs. Abstract Classes (Cont.)  Java allows for single inheritance for class extension, but multiple extensions for interfaces  An interface can inherit other interfaces using the extends keyword.  A class can extend its superclass and implement multiple interfaces. public class NewClass extends BaseClass implements Interface1, Interface2, …. InterfaceN { …. } 29

Abstract Classes & Interfaces  Example  Food is an abstract class. Can you make an instance of food? No. But you can make an instance of an apple or a steak, which are types of food. Food is the abstract concept; it shouldn’t exist.  Skills are ususally interfaces. Can you make an instance of a athlete or chef? No, but you can make an instance of a person, and have that person take on all these skills.

Abstract Classes & Interfaces  Q: So what’s the difference between an interface and an abstract class?  A:  An interface cannot implement any methods, whereas an abstract class can.  A class can implement many interfaces but can have only one superclass (abstract or not)  An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.  Syntax:  abstract class: public class Apple extends Food { … }  interface: public class Person implements Student, Athlete, Chef { … }

Abstract Classes & Interfaces  Q: Why are they useful?  A: By leaving certain methods undefined, these methods can be implemented by several different classes, each in its own way. Example: Chess Playing Program  an abstract class called ChessPlayer can have an abstract method makeMove(), extended differently by different subclasses. public abstract class ChessPlayer { public void makeMove();}  an interface called ChessInterface can have a method called makeMove(), implemented differently by different classes. public interface ChessInterface { public void makeMove();}

Abstract Classes & Interfaces  Q: Where else can interfaces be used?  A: You can pass an interface as a parameter or assign a class to an interface variable, just like you would to an abstract class. Example: Food myLunch = new Sandwich(); Food mySnack = new Apple(); Student steve = new Person(); //assuming that Person implements Student  If Person has methods eat(Food f) and teach(Student s), the following is possible: Person bob = new Person(); steve.teach(bob); steve.eat(myLunch); System.out.println(“Yum.”);

Examples 34  Look at L2.zip  Shape Example  Shape  Circle  Square  Cylinder  ShapeTestDriver  Student Example  Student  Name  UnderGrad  Grad  StudentTestDriver  Employee Example  Employee  EmployeeTestDriver  Name