Classes and Objects Including inheritance. OOP — Object-Oriented Programming In OOP system, the...

Post on 17-Jan-2016

254 views 7 download

Tags:

Transcript of Classes and Objects Including inheritance. OOP — Object-Oriented Programming In OOP system, the...

Classes and Objects

Including inheritance

OOP —Object-Oriented Programming

• In OOP system, the class is a fundamental unit.• An OOP program models a world of active objects.• An object may have its own “memory,” which may

contain other objects.• An object has a set of methods that can process

messages of certain types.

OOP (cont’d)• A method can change the object’s state,

send messages to other objects, and create new objects.

• An object belongs to a particular class, and the functionality of each object is determined by its class.

• A programmer creates an OOP application by defining classes.

The OOP Concepts:

• To be truly object oriented, a programming language should support at least three characteristics– Encapsulation– Polymorphism– Inheritance

The OOP Concept:Encapsulation

• It includes bundling of related data members and functions together to achieve– Information hiding and– Abstraction

• It ensures that its members are applied in the form of classes to form a single entity-the object.

The OOP Concept: Polymorphism

• Polymorphism (multiple forms) is the capability of a set of related objects/methods/functions to behave in similar but independent ways.

The OOP Concept: Inheritance• The objective of inheritance is the reusability of

existing or pre-written code• A programmer can define hierarchies of classes• More general classes are closer to the top

Person

Child Adult

Baby Toddler Teen

Superclass(Base class)

Subclass(Derived class)

subclass extends superclass

The OOP Concept in java

• Java provides support for OOP through– classes and – interfaces

Classes and Objects

• A class is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions.

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

Class Object• A blueprint for

objects of a particular type

• Defines the structure (number, types) of the attributes

• Defines available behaviors of its objects

Attributes

Behaviors

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 = “Maruti" color = Color.YELLOW numPassengers = 2 amountOfGas = 16.5

Behaviors:

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 the main method or a constructor or another method)

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

• Full library class names include the package name. For example:

java.awt.Color

javax.swing.JButton

• import statements at the top of the source file let you refer to library classes by their short names: import javax.swing.JButton;

...

JButton go = new JButton("Go");

Fully-qualified name

import (cont’d)

• 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; defines System, Math, Object, String, and other commonly used classes.

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

public class Foot{ private Image picture; private CoordinateSystem coordinates;

public Foot (int x, int y, Image pic) { picture = pic; coordinates = new CoordinateSystem (x, y, pic); }

public void moveForward (int distance) { coordinates.shift (distance, 0); }

public void moveSideways (int distance) { coordinates.shift (0, distance); } ...}

Fields

Constructor

Methods

Fields

• instance variables

• Constitute “private memory” of an object

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

• Each field has a name given by the programmer

private [static] [final] datatype name;

Fields (cont’d)

Usually private

May be present: means the field is a constant

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

You name it!

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

private Foot leftFoot;

Constructors

• Short procedures for creating objects of a class

• Always have the same name as the class• Initialize the object’s fields• May take parameters• A class may have several constructors that

differ in the number and/or types of their parameters

Constructors (cont’d)

public class Foot{ private Image picture; private CoordinateSystem coordinates;

public Foot (int x, int y, Image pic) { picture = pic; coordinates = new CoordinateSystem(x, y, pic); } ...}

The name of a constructor is always the same as the name of the class

A constructor can take parameters

Initializes fields

Constructors (cont’d)

public class Foot{

...

public Foot (int x, int y, Image pic) { ... } ...}

// FootTest.java ... Image leftShoe = ...; ... Foot leftFoot = new Foot (5, 20, leftShoe); ...

An object is created with the new operator

The number, order, and types of parameters must match

Constructor

Methods

• Call them for a particular object:

leftFoot.moveForward(20);

amy.nextStep( );

ben.nextStep( );

go.setText("Stop");

Methods (cont’d)

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

{

...

}

Methods (cont’d)

• A method can return a value to the caller

• The keyword void in the method’s header indicates that the method does not return any value

public void moveSideways(int distance) { ... }

Passing Parameters to Constructors and Methods

• Any expression that has an appropriate data type can serve as a parameter: double u = 3, v = -4; ... Polynomial p = new Polynomial (1.0, -(u + v), u * v); double y = p.getValue (2 * v - u);

public class Polynomial{ public Polynomial (double a, double b, double c) { ... } public double getValue (double x) { ... } ...

Passing Parameters (cont’d)

• A “smaller” type can be promoted to a “larger” type (for example, int to long, float to double).

• int is promoted to double when necessary:

The same as: (3.0)

... Polynomial p = new Polynomial (1, -5, 6); double y = p.getValue (3);

The same as: (1.0, -5.0, 6.0)

Passing Parameters (cont’d)

• Primitive data types are always passed “by value”: the value is copied into the parameter.

double x = 3.0; double y = p.getValue ( x );

public class Polynomial{ ... public double getValue (double u) { double v; ... }}

x: 3.0 u: 3.0copy

copy

u acts like a local variable in getValue

Passing Parameters (cont’d)public class Test{ public double square (double x) { x *= x; return x; }

public static void main(String[ ] args) { Test calc = new Test (); double x = 3.0; double y = calc.square (x); System.out.println (x + " " + y); }}

x here is a copy of the parameter passed to square. The copy is changed, but...

... the original x is unchanged.Output: 3 9

Passing Parameters (cont’d)• Objects are always passed as references:

the reference is copied, not the object. Fraction f1 = new Fraction (1, 2); Fraction f2 = new Fraction (5, 17);

Fraction f3 = f1.add (f2);

public class Fraction{ ... public Fraction add (Fraction f) { ... }}

copy reference

A Fraction object:

num = 5denom = 17

refers to the same object

refers to

Passing Parameters (cont’d)

• A method can change an object passed to it as a parameter (because the method gets a reference to the original object).

• A method can change the object for which it was called (this object acts like an implicit parameter):

panel.setBackround(Color.BLUE);

Passing Parameters (cont’d)

• Inside a method, this refers to the object for which the method was called. this can be passed to other constructors and methods as a parameter:

public class ChessGame { ... Player player1 = new Player (this); ...

A reference to this ChessGame object

return Statement

• A method, unless void, returns a value of the specified type to the calling method.

• The return statement is used to immediately quit the method and return a value:

return expression;

The type of the return value or expression must match the method’s declared return type.

return Statement (cont’d)

• A method can have several return statements; then all but one of them must be inside an if or else (or in a switch):

public someType myMethod (...){ ... if (...) return <expression1>; else if (...) return <expression2>; ... return <expression3>;}

return Statement (cont’d)

• A boolean method can return true, false, or the result of a boolean expression:

public boolean myMethod (...){ ... if (...) return true; ... return n % 2 == 0;}

return Statement (cont’d)

• A void method can use a return statement to quit the method early:

public void myMethod (...){ ... if (...) return; ...}

No need for a redundant return at the end

return Statement (cont’d)• If its return type is a class, the method returns a

reference to an object (or null).• Often the returned object is created in the method

using new. For example:

• The returned object can also come from a parameter or from a call to another method.

public Fraction inverse () { if (num == 0) return null; return new Fraction (denom, num); }

Overloaded Methods

• Methods of the same class that have the same name but different numbers or types of parameters are called overloaded methods.

• Use overloaded methods when they perform similar tasks: public void move (int x, int y) { ... }

public void move (double x, double y) { ... }public void move (Point p) { ... }

public Fraction add (int n) { ... }public Fraction add (Fraction other) { ... }

Overloaded Methods (cont’d)• The compiler treats overloaded methods as

completely different methods.• The compiler knows which one to call

based on the number and the types of the parameters passed to the method.

Circle circle = new Circle(5);circle.move (50, 100);Point center = new Point(50, 100);circle.move (center);

public class Circle{ public void move (int x, int y) { ... }

public void move (Point p) { ... } ...

Overloaded Methods (cont’d)

• The return type alone is not sufficient for distinguishing between overloaded methods.

public class Circle{ public void move (int x, int y) { ... }

public Point move (int x, int y) { ... } ...

Syntax error

Static Fields

• A static field (a.k.a. class field or class variable) is shared by all objects of the class.

• A non-static field (a.k.a. instance field or instance variable) belongs to an individual object.

Static Fields (cont’d)

• A static field can hold a constant shared by all objects of the class:

• A static field can be used to collect statistics or totals for all objects of the class (for example, total sales for all vending machines)

public class RollingDie{ private static final double slowDown = 0.97; private static final double speedFactor = 0.04; ...

Reserved words:

staticfinal

Static Fields (cont’d)

• Static fields are stored with the class code, separately from instance variables that describe an individual object.

• Public static fields, usually global constants, are referred to in other classes using “dot notation”: ClassName.constName

double area = Math.PI * r * r;setBackground(Color.BLUE);c.add(btn, BorderLayout.NORTH);System.out.println(area);

Static Fields (cont’d)

• Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods).

• If a class has only static fields, there is no point in creating objects of that class (all of them would be identical).

• Math and System are examples of the above. They have no public constructors and cannot be instantiated.

Static Methods

• Static methods can access and manipulate a class’s static fields.

• Static methods cannot access non-static fields or call non-static methods of the class.

• Static methods are called using “dot notation”: ClassName.statMethod(...)

double x = Math.random(); double y = Math.sqrt (x); System.exit();

Static Methods (cont’d)public class MyClass{ public static final int statConst; private static int statVar; private int instVar; ... public static int statMethod(...) { statVar = statConst; statMethod2(...);

instVar = ...; instMethod(...); }

Errors!

OK

Static method

Static Methods (cont’d)

• main is static and therefore cannot access non-static fields or call non-static methods of its class:

public class Hello{ private int test () { ... }

public static void main (String[ ] args) { System.out.println (test ()); }}

Error:non-static method test is called from static context (main)

Non-Static Methods

• A non-static method is called for a particular object using “dot notation”:

objName.instMethod(...);

• Non-static methods can access all fields and call all methods of their class — both static and non-static.

vendor.addMoney(25); die1.roll();

Inheritance

• In OOP a programmer can create a new class by extending an existing class

Superclass(Base class)

Subclass(Derived class)

subclass extends superclass

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

public class Pacer extends Walker{ public Pacer (int x, int y, Image leftPic, Image rightPic) { super (x, y, leftPic, rightPic); }

public void turnAround () { Foot lf = getLeftFoot (); Foot rf = getRightFoot (); lf.turn (180); rf.turn (180); lf.moveSideways (-PIXELS_PER_INCH * 8); rf.moveSideways (PIXELS_PER_INCH * 8); }}

A new method

Calls Walker’s constructor using super

Constructor

Calls Walker’s accessor methods

public class Walker{ ... public int distanceTraveled() { return stepsCount * stepLength; } ...}

Overrides Walker’s distanceTraveled method

public class Slowpoke extends Walker{ ... public int distanceTraveled() { return super.distanceTraveled ( ) / 10; } ...}

Calls superclass’s distanceTraveled method

Inheritance

• Java supports single inheritance only ( multiple inheritance not available)– So each class can have only one super class – But a class can have multiple sub classes

• Multilevel inheritance can be implemented by extending the child class(of a parent class) in a sibling class.

Inheritance

• Inheritance represents the IS-A relationship between objects: an object of a subclass IS-A(n) object of the superclass.

Superclass(Base class)

Subclass(Derived class)

Subclass extends Superclass

Class Hierarchies

• Using inheritance, a programmer can define a hierarchy of classes.

Biped

Walker Hopper Dancer

ToedInWalker CharlieChaplin

Class Hierarchies (cont’d)

• Help reduce duplication of code by factoring out common code from similar classes into a common superclass.

Biped Constructor Accessors turnLeft turnRight turnAround draw

Walker Constructor firstStep nextStep stop distanceTraveled

Hopper Constructor firstStep nextStep stop distanceTraveled

Class Hierarchies (cont’d)• Help reduce duplication of code by letting you

write more general methods in client classes.

public void moveAcross (Walker creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }

public void moveAcross (Hopper creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }

public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }

Works for either Walker or Hopperdue to polymorphism

Polymorphism

• Ensures that the correct method is called for an object of a specific type, even when that object is disguised as a reference to a more generic type, that is, the type of the object’s superclass or some ancestor higher up the inheritance line.

• Once you define a common superclass, polymorphism is just there no need to do anything special.

Polymorphism (cont’d)

public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled () < distance) creature.nextStep(); creature.stop(); }

The actual parameter passed to this method can be a Walker, a Hopper, etc. any subclass of Biped.

Correct methods will be called automatically for any specific type of creature: Walker’s methods for Walker, Hopper’s for Hopper, etc.

Abstract Classes• Some of the methods in a class can be declared

abstract and left with only signatures defined• A class with one or more abstract methods must

be declared abstract

public abstract class Biped{ ... public abstract void firstStep(); public abstract void nextStep(); public abstract void stop(); ... public void draw(Graphics g) { ... }}

Abstract methods

Abstract Classes (cont’d)

• Abstract classes serve as common superclasses for more specific classes

• An abstract method provides an opportunity for the compiler to do additional error checking

• Abstract classes and methods are needed for polymorphism to work

• Abstract classes are closer to the root of the hierarchy; they describe more abstract objects

Abstract Classes (cont’d) Object

... Component ... Button TextComponent Container ... JComponent Window ... JTextComponent AbstractButton JPanel ... ... JTextArea JTextField ... JMenuItem JButton ...

A fragment of Java library GUI class hierarchy (abstract classes are boxed)

Abstract Classes (cont’d)

• Java does not allow us to instantiate (that is, create objects of) abstract classes

• Still, an abstract class can have constructors they can be called from constructors of subclasses

• A class with no abstract methods is called concrete

Class Object

• In Java every class by default extends a library class Object (from java.lang)

• Object is a concrete class

public class Object{ public String toString {...} public boolean equals (Object other) {... } public int hashCode() { ... }

// a few other methods ...}

Methods redefined (overridden) as necessary

Calling Superclass’s Constructors

public class Walker extends Biped{ // Constructor public Walker(int x, int y, Image leftPic, Image rightPic) { super(x, y, leftPic, rightPic); ... }}

Biped

Walker

Calls Biped’s constructor

If present, must be the first statement

The number / types of parameters passed to super must match parameters of one of the superclass’s constructors.

Calling Superclass’s Constructors (cont’d)

• One of the superclass’s constructors is always called, but you don’t have to have an explicit super statement.

• If there is no explicit call to super, then superclass’s no-args constructor is called by default.

Must be defined then. If not defined syntax error: cannot find symbol : constructor ...

Calling Superclass’s Constructors (cont’d)

• Superclass’s constructor calls its superclass’s constructor, and so on, all the way up to Object’s constructor.

Biped

Walker

Objectsuper( )

super(...)

Calling Superclass’s Methods

public class CharlieChaplin extends Walker{ ... public void nextStep () { turnFeetIn(); super.nextStep(); turnFeetOut(); } ...}

Walker

CharlieChaplin

Calls Walker’s nextStep

super.someMethod refers to someMethod in the nearest class, up the inheritance line, where someMethod is defined.

Calling Superclass’s Methods (cont’d)

• super. calls are often used in subclasses of library classes:

public class Canvas extends JPanel{ ... public void paintComponent (Graphics g) { super.paintComponent (g); ... } ...

Interfaces

DanceFloor

DanceGroup

ControlPanel

Band

Dancer

Aerobics

Waltz

Rumba

Cha-Cha-Cha

Salsa

Dance

Interface

Interfaces (cont’d)• An interface in Java is like an abstract class,

but it does not have any fields or constructors, and all its methods are abstract.

• “public abstract” is not written because all the methods are public abstract.

public interface Dance{ DanceStep getStep (int i); int getTempo (); int getBeat (int i);}

Interfaces (cont’d)• We must “officially” state that a class implements

an interface.• A concrete class that implements an interface must

supply all the methods of that interface.

public class Waltz implements Dance{ ... // Methods: public DanceStep getStep (int i) { ... } public int getTempo () { return 750; } public int getBeat (int i) { ... } ...}

Interfaces (cont’d)

• A class can implement several interfaces.• Like an abstract class, an interface supplies a secondary

data type to objects of a class that implements that interface.

• You can declare variables and parameters of an interface type.

• Polymorphism fully applies to objects disguised as interface types.

Dance d = new Waltz( );

Interfaces (cont’d)public interface Edible{ String getFoodGroup(); int getCaloriesPerServing();}

public class Breakfast{ private int myTotalCalories = 0; ... public void eat (Edible obj, int servings) { myTotalCalories += obj.getCaloriesPerServing () * servings; } ...}

Polymorphism: the correct method is called for any specific type of Edible, e.g., a Pancake

public class Pancake implements Edible{ ...}

Classes Interfaces

• A superclass provides a secondary data type to objects of its subclasses.

• An abstract class cannot be instantiated.

• An interface provides a secondary data type to objects of classes that implement that interface.

• An interface cannot be instantiated.

Similarities

Classes Interfaces

• A concrete subclass of an abstract class must define all the inherited abstract methods.

• A class can extend another class. A subclass can add methods and override some of its superclass’s methods.

• A concrete class that implements an interface must define all the methods specified by the interface.

• An interface can extend another interface (called its superinterface) by adding declarations of abstract methods.

Similarities

Classes Interfaces

• A class can extend only one class.

• A class can have fields.

• A class defines its own constructors (or gets a default constructor).

• A class can implement any number of interfaces.

• An interface cannot have fields (except, possibly, some public static final constants).

• An interface has no constructors.

Differences

Classes Interfaces

• A concrete class has all its methods defined. An abstract class usually has one or more abstract methods.

• Every class is a part of a hierarchy of classes with Object at the top.

• All methods declared in an interface are abstract.

• An interface may belong to a small hierarchy of interfaces, but this is not as common.

Differences

OOP Benefits

• Facilitates team development

• Easier to reuse software components and write reusable software

• Easier GUI (Graphical User Interface) and multimedia programming