Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility...

25
Inheritance Contents 1. Fundamentals 2. Generalization 3. Constructors and Derived Classes 4. Visibility Modifiers 5. Abstract Classes 6. Interfaces

Transcript of Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility...

Page 1: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Contents

1. Fundamentals

2. Generalization

3. Constructors and Derived Classes

4. Visibility Modifiers

5. Abstract Classes

6. Interfaces

Page 2: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Fundamentals

Page 3: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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.

class A class B extends A

Base class Derived class

Base class attributes attributes inherited from base

Additional attributes

Base class methodsmethods inherited from base

Additional methods

Page 4: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

class Dog extends Animal class Cat extends Animal

class Animal

protected String name, sound;

protected double xpos, ypos;

public Animal(String n, String s) {..}

public void speak( ) {..}

public void moveTo(double x,double y){..}

public double getX( ) {..}

public double getY( ) {..}

class name

attributes (data)

methods (behavior)

public Dog(String n) {..}

public void chaseCats(Cat c){.}

public Cat(String n) {..}

public void runAway( ) {..}

//no additional attributes //no additional attributes

Base class

Derived classes

Derived classes have their own constructors

Derived classes may add their own unique behaviors

Page 5: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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!

Page 6: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Generalization

Page 7: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Generalization

Consider two classes A and B that have some common features

Features of A common to B

Features belonging only to A

Features belonging only to B

class B

attribute1attribute3

method1

method2

method4

class A

attribute1

method1

method2

method3

attribute2

Extract common features of A and B and put in new class C

class C

attribute1

method1

method2

Let classes A and B inherit from class C

class A extends C

attribute2

method3

class B extends C

attribute3

method4

Classes A and B extend C with features particular to each

Page 8: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Constructors for Derived Classes

Page 9: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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.

public class 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

Page 10: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Constructors for derived classes

public class 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);

}

public void chaseCats(Cat theCat) {

moveTo(theCat.getX( ), theCat.getY( ));

theCat.runAway( );

}

//inherits all other behavior from Animal

}

Client code in an application

Dog lassie = new Dog( );

Invokes the default constructor (even if one is not supplied by the coder).

default constructor of base class will be implicitly invoked

Dog lassie = new Dog(“Lassie”);

Dog lassie = new

Dog(“Lassie”, 2.5, 3.0);

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

Page 11: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Visibility Modifiers

Page 12: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Visibility modifiers

class A

private int mySecret;

private void swap(Object x, Object y);

protected int familySecret;

protected void sort( );

public void arrange( );

public int getMySecret( );

public void setMySecret( );

private features are accessible only to all member functions of the class.

method swap( ) is used internally by sort( )

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.

Page 13: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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.

Page 14: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Abstract Classes

Page 15: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Abstract Classes

An abstract class is one with at least one method that is abstract. It must be qualified as abstract.

public abstract class Shape {

private String name;

public Shape (String shapeName) {

name = shapeName;

}

public abstract double area( );

public abstract double perimeter( );

public String toString( ) {return name; }

}

Abstract methods – How does one find the area or perimeter of a shape?

A class with abstract methods must be qualified abstract

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.

Page 16: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Abstract classes

public abstract class Shape {

private String name;

public Shape (String shapeName) {

name = shapeName;

}

public abstract double area( );

public abstract double perimeter( );

public String toString( ) {

return name; }

}

public class Rectangle extends Shape {

protected double length, width;

public Rectangle(double len, double w) {

super(“Rectangle”);

length = len; width = w; }

public double area( ) {return length * width; }

public double perimeter( )

{return 2*(length+width); }

}

public class Circle extends Shape {

protected double radius;

public Circle (double rad) {

super(“Circle”); radius = rad; }

public double area( )

{return Math.PI*radius*radius; }

public double perimeter( )

{return 2.0* Math.PI * radius; }

}

Abstract base class ShapeImplemented by concrete derived classes that override the abstract methods area( ) and perimeter( )

Call base constr. first

Page 17: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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.

Page 18: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

interfaces

Page 19: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.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.

Page 20: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Interface

public interface Comparables {

public boolean lessThan(Object x);

public boolean greaterThan(Object x);

}

public class Rectangle extends Shape,

implements Comparables {

//methods and attributes from previous slide

public boolean lessThan(Object x) throws

IncompatibleTypeException{

if ( x instanceof Rectangle)

return area( ) < x.area( );

else throw new

IncompatibleTypeException( ); }

//similarly for method greaterThan( )

} public class Complex implements Comparables {

private double re, im, modulus, theta;

//other methods

public boolean lessThan(Object x) throws

IncompatibleTypeException {

if (x instanceof Complex)

return modulus < x.modulus;

else throw new IncompatibleTypeX ( ); }

}

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.

A class may extend exactly one base class AND implement multiple interfaces.

An interface may be implemented by very different kinds of classes

Page 21: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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.

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.

A class that implements an interface must implement ALL of the methods in the interface.

Page 22: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance

Interfaces

A class may implement multiple interfaces

public interface Scalable {

public void scale(double amt);

}

public class Rectangle extends Shape,

implements Comparables, Scalable {

private double length, width;

//methods previously developed

public void scale(double amt) {

length *= amt; width *= amt;

}

}

Java classes can extend only one class, but they can implement multiple interfaces.

Page 23: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Interfaces

An interface can inherit from another interface.

public interface MyInterface2 extends MyInterface1 {

public void myNewMethod(double param);

}

A derived class will implement all of the interfaces of the base

public class Base implements

InterfaceA, InterfaceB {

//base class attributes

//base class methods

//base class implements methods

// of the two interfaces

}

public class Derived extends Base {

//implement interfaces A and B too!

//my additional attributes and methods

}

Page 24: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

Inheritance Interfaces

One may use the fact that the data fields (attributes) in an interface are static and final to create “enumerated types”

public interface 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;

}

Attributes in an interface are automatically public in scope.Note that constants in java are capitalized by conventionIn an application you may have code that uses this interface

if (!(Months.MAY || Months.JUNE || Months.JULY || Months.AUGUST))

System.out.println(“Eat Oysters! “);

Page 25: Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.

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.