250 likes | 376 Views
Inheritance. Contents . Fundamentals Generalization Constructors and Derived Classes Visibility Modifiers Abstract Classes Interfaces. Inheritance . Fundamentals . class A. class B extends A. Inheritance .
E N D
Inheritance Contents • Fundamentals • Generalization • Constructors and Derived Classes • Visibility Modifiers • Abstract Classes • Interfaces
Inheritance Fundamentals
class A class B extends A Inheritance A derived class extends a base class. It inherits all of its methods (behaviors) and attributes (data) and it may have additional behaviors and attributes of its own. Derived class Base class Base class attributes attributes inherited from base Additional attributes Base class methods methods inherited from base Additional methods
class name class Animal protected String name, sound; protected double xpos, ypos; attributes (data) public Animal(String n, String s) {..} public void speak( ) {..} public void moveTo(double x,double y){..} public double getX( ) {..} public double getY( ) {..} methods (behavior) class Dog extends Animal class Cat extends Animal Inheritance Base class Derived classes have their own constructors Derived classes may add their own unique behaviors Derived classes //no additional attributes //no additional attributes public Dog(String n) {..} public Cat(String n) {..} public void chaseCats(Cat c){.} public void runAway( ) {..}
Inheritance Inheritance expresses an is-a association between two (or more) classes. A derived class object inherits ALL of the attributes and behaviors of the base class and may have additional features {attributes and/or behaviors} of its own. This is what is conveyed by the keyword extends. A derived class should NOT inherit from a base class to obtain some, but not all, of its features. Such a use of inheritance is possible in Java (and is done in practice all too frequently), but it is an incorrect use of inheritance and should be avoided! Instead of inheriting to extract some, but not all, of the features of a parent class, extract out (generalize) the common features of the two classes and place them in a third class from which the other two both inherit. Generalization pertains only to classes you build yourself. You don’t have the ability to generalize standard library classes!
Inheritance Generalization
Features of A common to B class A Features belonging only to A attribute1 Features belonging only to B attribute2 method1 class C method2 attribute1 method3 method1 method2 class B attribute1 attribute3 class A extends C class B extends C method1 method2 attribute2 attribute3 method4 method3 method4 Inheritance Generalization Extract common features of A and B and put in new class C Classes A and B extend C with features particular to each Let classes A and B inherit from class C Consider two classes A and B that have some common features
Inheritance Constructors for Derived Classes
Inheritance Constructors for derived classes In the previous example, the constructor for the base class Animal takes two string parameters from the client to initialize its attributes name and sound. publicclass Animal { portected String name, sound; protected double xPos, yPos; public Animal( ) { //default constructor name = “”; sound = “mute”; xPos = 0.0; yPos = 0.0; } public Animal(String myName, String mySound) { name = myName; sound = mySound; xPos = 0.0; yPos = 0.0; } public Animal(String myName, String MySound, double myX, double myY) { name = myName; sound = mySound; xPos = myX; yPos = myY;} //other methods of class Animal The constructor may be overloaded with different parameters
default constructor of base class will be implicitly invoked Dog lassie = new Dog(“Lassie”); Dog lassie = new Dog(“Lassie”, 2.5, 3.0); Inheritance Constructors for derived classes Client code in an application publicclass Dog extends Animal { //inherits attributes of Animal and add no additional ones public Dog( ) { } public Dog(String myName) { super (myname, “Bow-wow”); } public Dog(String myName, double myX, double myY) { super (myName, “Bow-wow”, myX, myY); } publicvoid chaseCats(Cat theCat) { moveTo(theCat.getX( ), theCat.getY( )); theCat.runAway( ); } //inherits all other behavior from Animal } Dog lassie = new Dog( ); Invokes the default constructor (even if one is not supplied by the coder). The derived class must initialize the inherited attributes of the base class by invoking its constructor with a call to super. (This must be the first statement in the constructor.)
Inheritance Visibility Modifiers
private features are accessible only to all member functions of the class. protected features are also available to methods of a derived class. public features can be accessed by client code as well as methods of the base and derived classes. Inheritance Visibility modifiers class A privateint mySecret; privatevoid swap(Object x, Object y); method swap( ) is used internally by sort( ) protectedint familySecret; protectedvoid sort( ); publicvoid arrange( ); publicint getMySecret( ); publicvoid setMySecret( );
Inheritance Visibility modifiers In the previous example we assumed that the private method swap( ) was used internally by sort( ) and that method arrange( ) was implemented by calls to sort( ). • Methods of derived classes cannot directly access swap( ), but they do have access to sort( ) that uses swap( ) internally. • Client code (applications) can access method arrange( ) that uses sort( ) and indirectly swap( ) internally. • Derived classes can override any protected methods from the base and change the visibility to public – the “public” gets access to the overriden method in the derived class, but not the original sort( ) method defined in the base class. • If a derived class overrides method sort( ), it cannot use the swap( ) method that was used in the base class.
Inheritance Abstract Classes
A class with abstract methods must be qualified abstract Abstract methods – How does one find the area or perimeter of a shape? Inheritance Abstract Classes An abstract class is one with at least one method that is abstract. It must be qualified as abstract. publicabstract class Shape { private String name; public Shape (String shapeName) { name = shapeName; } publicabstract double area( ); publicabstract double perimeter( ); public String toString( ) {return name; } } There can be no instances of abstract classes. An abstract class provides an interface that concrete classes (such as Circle and Rectangle in this example) can implement.
Call base constr. first Inheritance Abstract classes publicclass Rectangle extends Shape { protecteddouble length, width; public Rectangle(double len, double w) { super(“Rectangle”); length = len; width = w; } publicdouble area( ) {return length * width; } publicdouble perimeter( ) {return 2*(length+width); } } publicabstract class Shape { private String name; public Shape (String shapeName) { name = shapeName; } publicabstract double area( ); publicabstract double perimeter( ); public String toString( ) { return name; } } publicclass Circle extends Shape { protecteddouble radius; public Circle (double rad) { super(“Circle”); radius = rad; } publicdouble area( ) {return Math.PI*radius*radius; } publicdouble perimeter( ) {return 2.0* Math.PI * radius; } } Implemented by concrete derived classes that override the abstract methods area( ) and perimeter( ) Abstract base class Shape
Inheritance Abstract classes An abstract class: • “abstracts out” common behavior from a set of related classes that in the general case cannot be described by a common algorithm. • Provides a common interface for the client to any one of the classes in this related set. • Although instances of an abstract class such as Shape cannot be created, container classes can hold “Shape objects” and any one of the concrete realizations of Shape can be placed in the container. A container holding Shape(s) will hold objects of class Rectangle or Circle, or any other class that extends Shape.
Inheritance interfaces
Inheritance Interface An interface may be considered a “pure” abstract class. • It provides method names, parameter lists, and return types, none of which are implemented. • An interface may contain data fields (attributes), but they are implicitly static and final. • An interface provides to the client a description of what the classes that implement the interface must look like.
Inheritance Interface publicclass Rectangle extends Shape, implements Comparables { //methods and attributes from previous slide publicboolean lessThan(Object x) throws IncompatibleTypeException{ if ( x instanceof Rectangle) return area( ) < x.area( ); elsethrownew IncompatibleTypeException( ); } //similarly for method greaterThan( ) } publicinterface Comparables { publicboolean lessThan(Object x); publicboolean greaterThan(Object x); } One declares an interface in a manner similarly to the way in which one declares an abstract class. The qualifier interface is used instead of class and the methods do not have to be qualified as abstract. If the scope is public, the interface must be stored in a file of the same name. Any class that implements this interface must include the phrase implements Comparables In its header. publicclass Complex implements Comparables { private double re, im, modulus, theta; //other methods publicboolean lessThan(Object x) throws IncompatibleTypeException { if (x instanceof Complex) return modulus < x.modulus; elsethrownew IncompatibleTypeX ( ); } } A class may extend exactly one base class AND implement multiple interfaces. An interface may be implemented by very different kinds of classes
Inheritance Interfaces In the previous example, the classes Rectangle and Complex implemented the interface Comparables by first determining that the object being compared was an object of the same class, then performing a test on an appropriate attribute. A class that implements an interface must implement ALL of the methods in the interface. Note! Interface Comparables was developed here strictly for explanatory purposes. It could be created and implemented just as described, but it must be noted that there exists an interface Comparable found in java.util that has a single method – compareTo( ) – that returns a negative integer if less than, a positive integer if greater than, or 0 if equal to.
Inheritance Interfaces A class may implement multiple interfaces publicclass Rectangle extends Shape, implements Comparables, Scalable { privatedouble length, width; //methods previously developed publicvoid scale(double amt) { length *= amt; width *= amt; } } public interface Scalable { public void scale(double amt); } Java classes can extend only one class, but they can implement multiple interfaces.
Inheritance Interfaces An interface can inherit from another interface. publicinterface MyInterface2 extends MyInterface1 { publicvoid myNewMethod(double param); } A derived class will implement all of the interfaces of the base publicclass Derived extends Base { //implement interfaces A and B too! //my additional attributes and methods } publicclass Base implements InterfaceA, InterfaceB { //base class attributes //base class methods //base class implements methods // of the two interfaces }
Inheritance Interfaces One may use the fact that the data fields (attributes) in an interface are static and final to create “enumerated types” publicinterface Months { int JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4,MAY = 5, JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12; } In an application you may have code that uses this interface Note that constants in java are capitalized by convention Attributes in an interface are automatically public in scope. if (!(Months.MAY || Months.JUNE || Months.JULY || Months.AUGUST)) System.out.println(“Eat Oysters! “);
Inheritance Interfaces Since interfaces and abstract classes seem to be similar, when should I use each? • An interface gives you the benefits of an abstract class – “abstracting out” common behaviors particular to a set of classes and providing the client with a common set of signatures (method names, parameters, return types) – and of an interface – multiple inheritance. Therefore, whenever possible use an interface. If some of the methods in a base class must be concrete, then you must use an abstract class.