inheritance a review of objects, classes, and subclasses

34
Inheritance Inheritance A Review of Objects, Classes, and Subclasses

Upload: rosemary-gibson

Post on 14-Dec-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

InheritanceInheritance

A Review of

Objects, Classes, and Subclasses

Objects• Can model real-world objects

• Can represent GUI (Graphical User Interface)

components

• Can represent software entities (events, files,

images, etc.)

• Can represent abstract concepts (for example,

rules of a game, etc.)

Classes and Objects•A class is a piece of the program’s source code that describes a particular type of object. Object-Oriented programmers write class definitions.

•An object is called an instance of a class. A program can create and use more than one object or instance of the same class as needed.

•The word instance is a good word to represent an object because it indicates an object that exists for a period of time during part or all of the time a program is running.

Difference Between a Class and an Object

Characteristics

fields or instance variables

Behaviors

(methods)

Class Object

A blueprint for objects of a particular type … a cookie cutter.

Defines the structure (number, types) of the characteristics or attributes

Defines available behaviors of its objects

Class: Car Object: a car

Attributes: String model Color color int numPassengers double amountOfGas

Behaviors: Add/remove a passenger Get the tank filled Report when out of gas

Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5

Behaviors:

car calls methods of class as needed

Class vs. Object

• A piece of the program’s source code

• Written by a programmer

• An entity in a running program

• Created when the program is running (by a constructor or another method in a driver program or other file)

Class vs. Object

• Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects

• Specifies the possible behaviors of its objects

• Holds specific values of attributes or characteristics; these values can change while the program is running

• Behaves appropriately when called upon

Classes and Source Files

• Each class is stored in a separate file

• The name of the file must be the same as the name of the class, with the extension .java

public class Car{ ...}

Car.java By convention, the name of a class (and its source file) always starts with a capital letter.

(In Java, all names are case-sensitive.)

Libraries• Java programs are usually not written from

scratch.

• There are hundreds of library classes for all occasions.

• Library classes are organized into packages. For example:

java.util — miscellaneous utility classes

java.awt — windowing and graphics toolkit

javax.swing — GUI development package

Import Statements

• You can import names for all the classes in a package by using a wildcard .*:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

• java.lang is imported automatically into all classes and programs.

• java.lang defines System, Math, Object, String, and other commonly used classes. Its nice to not have to take the time to import these.

Imports all classes from awt, awt.event, and swing packages

public class SomeClass

• Fields

• Constructors

• Methods}

Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects

Procedures for constructing a new object of this class and initializing its fields

Actions that an object of this class can take (behaviors)

{

Class header

SomeClass.java

import ... import statements

FieldsThe word fields is used to represent not only instance variables

but also class variables and class constants. Specifically:

• Instance variables constitute the “private memory” of an object.

• Class variables are usually private, but class constants are

generally public.

• Each field has a data type (int, double, String, Image, etc.) Any

field can be an object of any type.

• Each field has a name given by the programmer that should

meaningfully describe its use.

private [static] [final] datatype name;

Types of Fields

May be present: means the field is a constant

int, double, etc., or an object: String, Image, SavingsAccount, etc.

You name it!

May be present: means the field is shared by all objects in the class

Usually private

FieldsExamples:

• private int pin; // private instance variable

• public static final double INTEREST_RATE = 0.025; // class

constant

• private static int numberOfAccounts;

The last example is a class variable. It is not an attribute of any object of the class, but rather it is an attribute of the class. The class (not any specific object) will maintain how many accounts have been created. Usually there is a public class method that allows a programmer to access its value.

Constructors

• Short procedures for creating objects of a class

• Always have the same name as the class

• Have the responsibility to initialize the object’s

fields

• May have parameters that pass off their values to

the fields

• A class may have several constructors that differ

in the number and/or types of their parameters

Constructor Parameters

public class SavingsAcount {

...

public SavingsAcount (int firstName, int lastName, int pin, …) { ... } ...}

// ATM_Test.java ... ... savings = new SavingsAcount (first, last, p, …); ...

The number, order, and types of parameters must match.

Constructor Code

Constructor Call

Constructors Documentation

JButton go = new JButton("Go");

A class’s API can show you how to use constructors of the class.

Methods of a Model Class• Methods of a Model class are called for a particular

object. In other words, in this form:

savings.deposit(amount);

checking.withdrawl(amount);

• These kind of methods are sometimes called instance methods. These methods do not contain the word static in their method signatures. They may be accessor or mutator methods.

• Class methods contain the word static in their method signatures and are usually called to obtain the value of a class variable.

Example of a Class MethodExample of a class method:

public static int getNumberOfAccounts ( )

{

return numberOfAccounts;

}

This method would return the value stored in the private class variable numberOfAccounts.

Parameters of Methods

• The number and types of parameters (a.k.a. arguments) passed to a method must match method’s parameters:

g.drawString ("Welcome", 120, 50);

public void drawString ( String msg, int x, int y )

{

...

}

Encapsulation and Information Hiding

• A class interacts with other classes only through constructors and public methods.

• Other classes do not need to know the mechanics of a class to use it effectively. In other words, a class doesn’t need to know the implementation details of how the code is written in another class.

• Encapsulation is the combining of attributes an behavior together to define an object. In other words, writing a model class to define the fields and methods needed for a particular kind of object. Encapsulation facilitates team work and program maintenance (making changes to the code).

The Scope of a Class’s Methods• A class’s constructors and methods can call other

public and private methods of the same class.

• However, a class’s constructors and methods can call only public methods of another class.

Class X

private field

private method

Class Y

public method public method

A method of one class can’t access any private items of another class.

Inheritance

In Object Oriented Programming, a programmer can create a new class by extending an existing class.

Superclass(Base class)

Subclass(Derived class)

subclass extends superclass

Subclasses

A subclass …

• inherits fields and methods of its superclass

• can add new fields and methods

• can redefine (override) a method of the superclass

• must provide its own constructors, but calls superclass’s constructors

• does not have direct access to its superclass’s private fields, but has access to protected fields

Sample Structure of Inheritance

Many times programmers will organize hierarchies of classes using an interface, a superclass and subclasses.

Interface

Super Class

Subclass Class 1 Subclass Class 2

You can think of the red arrow as meaning “inherits from”

Objects in a Bank Account Program

In a Bank Account program we might have a SavingsAccount and a CheckingAccount, but to keep from duplicating code we might have an AbstractAccount class to accumulate the code that would be the same in those classes. An interface could also serve to further organize objects of these types to standardize the type of accounts used for our purpose.

BankAccount Interface

AbstractAccount Class

SavingsAccount Class

CheckingAccount Class

You can think of the red arrow as meaning “inherits from”

Structure of an Interfacepublic interface BankAccount {

public String getFirstName();

public String getLastName();

public int getAccountNumber();

public double getBalance();

public double deposit (double d);

public double withdrawl (double d);}An interface is a listing of methods that must be implemented by

a class or another interface. (Yes it is possible to have a subinterface.) In the list, only the method signature of the method to be implemented followed by a semicolon is included for each method. Also, the interface definition line uses public interface instead of public class.

Declaring an Abstract ClassHere is the class definition line of an abstract class that

implements an interface.

abstract public class AbstractShape implements Shape

Notice it looks the same as a typical class definition line, except that the Java keyword abstract is added to the first of it.

One thing you can’t do is instantiate an object of an abstract class. Think about that. An object of an abstract class would really be an incomplete object. It would be a partial object that would contain only some parts of an object that might be constructed of a subclass. So it would be meaningless.

So to prevent an object of an abstract class from being constructed, we add the keyword abstract to the class definition line.

Final Methods of an Abstract Class

As mentioned previously, an abstract class is a super class that contains the code that would be duplicated in any subclasses.

An abstract class will contain fields and methods that would be the same for all subclasses that would extend it.

For the methods that would be the same in any subclass, we just need to code them once in the abstract class and not in the subclasses. To do this, we place the Java keyword final at the first of the method signature to indicate that the method can’t be overridden in a subclass.

If for some reason, you might want the method to be overridden in one class but not other subclasses, then you would leave off the word final.

Final Methods of AbstractShapeThese final methods were used in the AbstractShape class,

because the code would have been exactly the same in the Circle, Rectangle, or Triangle classes. So we place it in the AbstractShape class and make the methods final.

public final int getXPos() {

return xPos;

}

public final int getYPos() {

return yPos;

}

public final Color getColor() {

return color;

}

Abstract Methods of an Abstract ClassFor methods that will be provided by subclasses, we just provide

the method signature along with the word abstract and a

semicolon to end the method signature. No code or curly

braces are included.

If the abstract class implements an interface, it is necessary to

include the word abstract with methods like this so Java

knows that the subclass will be providing the method. By

implementing the interface, Java is forcing the abstract class

to implement the method. So if is not going to provide the

method, then it must have the method signature with abstract

so Java knows how it will be handled.

Abstract Methods of the AbstractShape ClassThese abstract methods were used in the AbstractShape class,

because the code for each one in the Circle, Rectangle, and Triangle classes was different. Therefore the AbstractShape class couldn’t provide each method’s code.

abstract public double area();

abstract public void draw (Graphics g);

abstract public void paint (Graphics g);

abstract public void move (int xLoc, int yLoc);

abstract public void stretchBy (int factor);

Using the Super Keyword in JavaWhen super is used inside a constructor, it must be the first line

of code.

If it is in the default constructor of a subclass and you write:

super( );

then you are calling the default constructor of the superclass.

If it is in an initializing constructor, and you need to pass

parameters up to the superclass, then you will be calling the

initializing constructor of the superclass. The code might look

like this, but it still needs to be the first line of code:

super(xLoc, yLoc, r, c);

Using the Super Keyword in JavaWhen super is used inside any other method, it doesn’t have to

be the first line of code.

If it is in the draw method of a subclass and you write:

super.draw(g);

when you are calling the draw method of the super class, then it

can be any place in the method.