340 likes | 519 Views
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. Object Oriented Programming (OOP) .
E N D
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
Object Oriented Programming (OOP) • 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 • 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 • 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 • 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 • 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 • 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
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.
Class level access modifiers (java classes only) • 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) • All the 4 public, private, protected and no modifieris 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 anypackage
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 { intradius; // instance variable publicCircle(intr) { radius = r; } public intgetRadius() { returnradius; } 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.’
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. 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 class Circle { intradius; // instance variable static intcount = 6; publicCircle(intr) { radius = r; count ++; } public void printCount() { System.out.println(count); } } • All object of class ‘Circle’ share 1 copy of static variable ‘count’.
Static Methods • Methods that operate on static variables are declared static class Circle { intradius; // instance variable static intcount = 6; // static variable public Circle(intr) { radius = r; count ++; } public static void printCount() { System.out.println(count); } } 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. class Circle { intradius; // instance variable static intcount = 0; // static variable public Circle(intr) { radius = r; count += 1; } public static void printCount() { System.out.println(count); } } Circle c1; Circle.printCount(); // 0 Circle c2 = new Circle(8); c2.printCount(); // 1 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. getPerimeter() and getCircle() are common features of geometric objects getArea(); getPerimeter(); getArea(); getPerimeter(); getWidth(); getHieght(); getArea(); getPerimeter(); getRadius();
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. public abstract class Vehicle {Stringname; public String getName() { returnname; \\ 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.
Java Interface • A Java interfaceis 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
interface is a reserved word Interface: Syntax public interface Doable { public static final String NAME; public void doThis(); public intdoThat(); public void doThis2 (float value, charch); public booleandoTheOther (intnum); } No method in an interface has a definition (body)
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
implements is a reserved word Each method listed in Doable is given a definition Implementing Interfaces public class Something implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } public class ManyThingsimplements Doable, AnotherDoable
Polymorphism via Interfaces • Define a polymorphism reference through interface • declare a reference variable of an interface typeComparable obj; • the obj reference can be used to point to any object of any class that implements the Comparableinterface • the version of compareTodepends on the type of object that obj is referring to: obj.compareTo();
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 (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 NewClassextendsBaseClass implements Interface1, Interface2, …. InterfaceN { …. }
Abstract Classes & Interfaces • Example • Foodis 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 classApple extends Food { … } • interface: public class Person implementsStudent, 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 { <variable declarations> <method declarations> public void makeMove(); } • an interface called ChessInterfacecan 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 • Look at L2.zip • Shape Example • Shape • Circle • Square • Cylinder • ShapeTestDriver • Student Example • Student • Name • UnderGrad • Grad • StudentTestDriver • Employee Example • Employee • EmployeeTestDriver • Name