Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Abstract Classes and Interfaces Lecture 2 – 9/6/2012."— Presentation transcript:

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

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

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

4 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

5 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

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

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

8 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

9 Composition Example 9

10 Inheritance Example 10

11 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

12 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’.

13 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

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

15 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

16 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

17 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

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

19 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

20 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! }

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

28 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

29 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

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

31 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 { … }

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

33 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.”);

34 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


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

Similar presentations


Ads by Google