application development with java lecture 21. inheritance subclasses overriding object class

53
Application development with Java Lecture 21

Upload: henry-richardson

Post on 29-Jan-2016

223 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Application development with Java

Lecture 21

Page 2: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Inheritance

• Inheritance

• Subclasses

• Overriding

• Object class

Page 3: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Inheritance Idea

• Creation of new software from existing software components by adding only.

• You create objects of your class inside a new class.

• This is called composition.• New class composed of objects of existing

classes.

Page 4: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Superclass and Subclass

• Inheritance allows us to derive new classes from existing ones.

• The existing class is called superclass.• The class that does the inheriting is said to be

a subclass of the class from which it inherits.• Sometimes the terms derived class and base

class are used instead of subclass and superclass.

Page 5: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Inheritance

• Instances of the derived class inherits all the properties and functionality that are defined in base class.

• A derived class can add to the state and behavior that it inherits.

• It can also replace or modify inherited behavior.

Page 6: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Example

Point(superclass)

ColoredPoint(subclass)

z

Employee(superclass)

Boss(subclass)

3DColoredPoint(subclass)

z

Shape(superclass)

Rectangle(subclass)

Oval(subclass)

Some examples of superclasses and subclasses:

Page 7: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Rules of Thumb

• Inheritance creates is-a relation.– if x is-a y - than x could extend y

• ColoredPoint is a Point.• Everything that can be done with a Point

object can be done with ColoredPoint object.

• ColoredPoint has all the functionality of a Point and some more.

Page 8: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Example

Point(superclass)

ColoredPoint(subclass)

data:xy

methods:set(int newx,int newy)getx()gety()

data:xycolor

methods:set(int newx,int newy)getx()gety()setcolor(int color)

Page 9: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Another example

Student - is a person who studies in the university or college.

CS Student - is a person who studies computer science in the university or college.

CS female Student – is a person who studies computer science in the university or college and it’s gender is female.

 

Page 10: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Student

CS Student

CS FemaleStudent

CS FemaleStudent in

IDC

• Student is a superclass of CS Student is a superclass CS female Student is a superclass CS female student in IDC.

• CS female student in IDC is a subclass of CS female Student is a subclass of CS Student is a subclass of Student.

Another example

Page 11: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Creating a subclass• A keyword extends used to show that the current class is

a subclass of other class. • Usually we try to extend the superclass data and methods

by adding new features.Syntax:class class_name extends super_class_name{ // additions to, and modifications of stuff inherited // from super class }

Page 12: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Example

/*** A ColoredPoint class represents a Point object * with new data field color.*/public class ColoredPoint extends Point{private Color color;// … }

Page 13: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Example

• Subclass can also have new methods.

public class ColoredPoint extends Point

{

private Color color;

 // new method

void setColor(Color color)

{ this.color = color; }

}

Page 14: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Subclass• When you derive a class from a given base

class:– The subclass inherits all the fields of the base class– It inherits all the methods of the base class

• Private fields and methods in the base class are inherited but they cannot be accessed directly from the code of the subclass.

• They are private and encapsulated in the base class itself.

Page 15: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Subclass methods

• Subclass can do one of the following with each inherited method:

• use the method as it is

• change it’s implementation – override

• Subclass can also have methods and data of his own, i.e. add methods.

Page 16: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Example

data :xy

methods :set(int newx,int newy)getx()gety()

Point

additional data :color

additional methods :setcolor(Color color)

ColoredPoint

Page 17: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Constructors

• Constructors are not inherited.

• Constructors must be redefined.

• We often want to use the parent's constructor to set up the "parent's part" of the object.

• We do this by using the super keyword.

Page 18: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Example

public class ColoredPoint extends Point{ …// constructorpublic ColoredPoint(int x, int y,Color color){ super(x,y);this.color=color; }}

Constructor of the Point class

Page 19: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

The super keyword• The keyword super allows to refer to the parent

(super) class.• The super keyword can be used to access the

method from the subclass.• The first line of the constructor must invoke one

of superclass constructors using super(..). • If you do not call super(..) in the first line of the

constructor the compiler automatically invoke the empty constructor of the superclass.

Page 20: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

The default constructor

• The default constructor is empty constructor.• If a given class does not have a constructor a

default constructor is used by the compiler.• If a subclass does not have a constructor then an

empty constructor of superclass is invoked and an empty constructor of subclass itself.

Page 21: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Super(..)

• A subclass constructor needs to indicate which parent constructor to connect to.

Example: super(x,y); // uses two integer constructor of Point

super(); // uses default constructor

Page 22: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Super(..) and methods

• The major use of super is to override a method with a new method that extends the behavior of the inherited method.

• The new method can use super to call the inherited method, and it can include additional code to provide additional behavior.

• Syntax:

super.method();

Page 23: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

The super keywordpublic class ColoredPoint extends Point {…// ColoredPoint constructor spublic ColoredPoint(int x, int y,Color color){ super(x,y); // constructor of the Point classthis.color=color; // additional information }public ColoredPoint(int x, int y){ super(x,y); // constructor of the Point class}…}

Page 24: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Overriding

• Overriding means changing the implementation of the method while keeping it’s signature.

• Subclass can override a method implementation to provide a different version than parent.

• Subclass can add some information to parent version of the method.

• Subclass can completely re-define the parent’s method.

Page 25: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

File

RestrictedFile

File(String name) isOpen() open() close() getName()

RestrictedFile(String name, long key) isLocked() lock() unlock(long key)

Overriding

• Example: We want clients to be able to open a protected file only if it is unlocked

Page 26: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

File Example/** * Part of a File implementation */public class File { // The name of the file private String name; // true if the file is opened private boolean isOpen;

/** * Construct a file with a given name. */ public File(String name) { this.name = name; }

Page 27: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

File Example

/** * Returns the name of the file. */ public String getName() { return name; }

/** * Checks if the file is open. * @return true iff the file is open */ public boolean isOpen() { return isOpen; } // other methods/variables...}

Page 28: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

File Example /** * Opens the file. */ public void open() { // … other operations isOpen = true; } /** * Closes the file. */ public void close() { // … other operations isOpen = false; }}

Page 29: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

RestrictedFile Example

/** * Represents a restricted file, which can be * opened only if it is unlocked. In order to * unlock the file a key is needed. */public class RestrictedFile extends File { // Password for unlocking the file private long key; // The state of the file - locked/unlocked private boolean isLocked;

Page 30: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

RestrictedFile Cont.

// Constructs a new restricted file. // The key is used to unlock the file public RestrictedFile

(String name, long key) { super(name); this.key = key; isLocked = true; } //Checks if the file is locked. public boolean isLocked() { return isLocked; }

Page 31: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

RestrictedFile Cont.

// Locks the file. public void lock() { isLocked = true; } // Unlock the file. // The file will be unlocked only // if the given key matches. public void unlock(long key) { if (this.key == key) { isLocked = false; } }

Page 32: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

RestrictedFile Cont.

// Unlock the file.

// The file will be unlocked only

// if the given key matches.

public void unlock(long key) {

if (this.key == key) {

isLocked = false;

}

}

Page 33: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Locking?

• So far the implementation is useless if we do not change the implementation of open()!

Page 34: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

RestrictedFile Overrides

// Open the file. The file will be

// opened only if it is unlocked.

public void open() {

if (!isLocked()) {

super.open();

}

}

Page 35: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Overriding in RestrictedFile

•RestrictedFile inherits the interface of File, but changes the functionality of the method open().•We say that RestrictedFile overrides the method open().•Notice the call to super.open() - we invoke the method open() of the superclass on this object. (what if we just write “open()”?)

Page 36: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Rules of Overriding– When you derive a class B from a class A, the

interface of class B will be a superset of that of class A (except for constructors).

– You cannot remove a method from the interface by subclassing (why?).

– However, class B can override some of the methods that it inherits and thus change their functionality.

– The contract of a method states what is expected from an overriding implementation of the method.

Page 37: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Visibility modifiers

• Visibility modifiers determine which class members get inherited and which do not, which members are accessible and which are not.

• Any member (variable,method and constructor) can be declared with one of the 4 visibility modifiers:– public– private– protected

Page 38: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Visibility modifiers (revisited)• public – accessible anywhere, inherited by all

subclasses of its class.• private – only code of the same class in which the

member has been defined can access this member, inherited by subclasses of its class but can not be accessed directly from the code of the subclass.

• protected – accessible by any class in the same package as its class, inherited by all subclasses of its class.

• default – accessible by any class in the same package as its class, inherited by any class in the same package.

Page 39: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

The final Modifier

•The final modifier can be used for classes, methods and variables, in each case it has a different meaning.

•A final variable can be initialized only once (constants).

•A final class can not have derived classes.

•A final method cannot be overridden.

Page 40: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Inheritance

• Several classes can be declared as subclasses of the same superclass.

• These subclasses share some structures and behaviors - the ones they inherit from their common superclass.

• The superclass expresses these shared structures and behaviors.

• Inheritance can also extend over several "generations" of classes.

Page 41: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Inheritance is Transitive

• In the diagram class E is a subclass of class D which is itself a subclass of class A. In this case, class E is considered to be a subclass of class A, even though it is not a direct subclass.

class C

class A

class B class D

class E

Page 42: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

The Object Class

• Java defines the class java.lang.Object that is defined as a superclass for all classes.

• All classes directly or indirectly extend the Object class.

• If a class does not specify explicitly which class it is derived from, then it will be implicitly derived from class Object.

• All classes inherit Object’s methods.

Page 43: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Point

ColoredPoint

Object

Hierarchy Diagram

•We can depict the relationship between this classes in the following diagram, that is called class hierarchy diagram.

Page 44: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

File

RestrictedFile

Object

Class Hierarchy Diagram: A Tree!

IOvalTurtle IPoint

Page 45: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

All Classes Extend Object

• The following two class definitions are equivalent:

class SomeClass extends Object

{

// some code

}

class SomeClass

{

// some code

}

Page 46: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Methods of Object Class

• The Object class defines a set of methods that are inherited by all classes.

• Some of them are: equals(Object o), getClass(), toString()

• toString() method that is used whenever we want to get a String representation of an object.

• When you define a new class, you can override the toString() method in order to have a suitable representation of the new type of objects as Strings.

Page 47: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

toString() Method

•The toString() method is used whenever we want to get a String representation of an object.

•When you define a new class, you can override the toString() method in order to have a suitable representation of the new type of objects as Strings.

Page 48: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

equals() Method

•The equals()method receives an Object as a parameter. Since all classes are derived from Object, every class “is an” Object. •The implementation just checks if the two references (this and obj) are the same.•You can override this method in order to fit your class logic (when are two points equal?, when are two URLs equal?)

Page 49: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Overloading Vs. Overriding

– Overloading deals with multiple methods in the same class with the same name but different signatures.

– Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature.

– Overloading lets you define a similar operation in different ways for different data.

– Overriding lets you define a similar operation in different ways for different object types.

Page 50: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Overriding toString() public class Point {private int x,y;

public Point(int x, int y){ this.x=x;

this.y=y; }

public int getx(){return x;}

public int gety(){return y;}

public String toString() { return "(" + x + "," + y + ")"; }

}

Page 51: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Overriding toString() public class ColoredPoint extends Point{private Color color;

public ColoredPoint(int x, int y,Color color) { super(x,y);

this.color=color; }

void setColor(Color color) { this.color = color; }

public String toString() { return "(" + getx() + "," + gety() + "," + color + ")"; }

}

Page 52: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Overriding toString() import java.awt.Color;

class PrintingPointExample { public static void main(String[] args) { ColoredPoint p = new ColoredPoint(2,3,Color.red);

System.out.println(p); }}

Page 53: Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class

Any Questions?