Transcript PPT2

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 entitythe 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
Superclass
(Base class)
Person
subclass extends
superclass
Child
Baby
Toddler
Adult
Teen
Subclass
(Derived class)
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
• A blueprint for
objects of a
particular type
• Defines the structure
(number, types) of
the attributes
• Defines available
behaviors of its
objects
Object
Attributes
Behaviors
Class: Car
Attributes:
String model
Color color
int numPassengers
double amountOfGas
Object: a car
Attributes:
model = “Maruti"
color = Color.YELLOW
numPassengers = 2
amountOfGas = 16.5
Behaviors:
Behaviors:
Add/remove a passenger
Get the tank filled
Report when out of gas
Class
• A piece of the
program’s source
code
• Written by a
programmer
vs.
Object
• An entity in a running
program
• Created when the
program is running
(by the main method
or a constructor or
another method)
Class
• 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
vs.
Object
• 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
Car.java
By convention, the
public class Car
{
...
}
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.*;
Imports all classes
from awt, awt.event,
and swing packages
• java.lang is imported automatically into all
classes; defines System, Math, Object,
String, and other commonly used classes.
SomeClass.java
import ...
import statements
public class SomeClass
{
• Fields
• Constructors
• Methods
}
Class header
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)
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
Fields (cont’d)
You name it!
private [static] [final] datatype name;
Usually
private
May be present:
means the field is
shared by all
objects in the class
int, double, etc., or an
object: String, Image,
Foot
May be present:
means the field
is a constant
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)
The name of a constructor
is always the same as the
name of the class
public class Foot
{
private Image picture;
private CoordinateSystem coordinates;
public Foot (int x, int y, Image pic)
{
A constructor can take parameters
picture = pic;
coordinates = new CoordinateSystem(x, y, pic);
}
...
}
Initializes fields
Constructors (cont’d)
// FootTest.java
...
An object is created with
Image leftShoe = ...;
the new operator
...
Foot leftFoot = new Foot (5, 20, leftShoe);
...
public class Foot
{
...
public Foot (int x, int y, Image pic)
{
...
}
...
}
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:
public void drawString ( String msg, int x, int y )
{
...
}
g.drawString ("Welcome", 120, 50);
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:
...
Polynomial p = new Polynomial (1, -5, 6);
double y = p.getValue (3);
The same
as: (3.0)
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 );
x:
3.0
public class Polynomial
{
copy
...
public double getValue (double u)
{
double v;
u acts like a
...
local variable
}
in getValue
}
copy
u:
3.0
Passing Parameters (cont’d)
public class Test
{
public double square (double x)
{
x here is a copy of the parameter
x *= x;
passed to square. The copy is
return x;
changed, but...
}
public static void main(String[ ] args)
{
Test calc = new Test ();
... the original x
double x = 3.0;
is unchanged.
double y = calc.square (x);
Output: 3 9
System.out.println (x + " " + y);
}
}
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);
public class Fraction
{
... copy reference
Fraction f3 = f1.add (f2);
refers to
A Fraction
object:
num = 5
denom = 17
public Fraction add
(Fraction f)
{
...
}
refers to the
}
same object
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:
public Fraction inverse ()
{
if (num == 0)
return null;
return new Fraction (denom, num);
}
• The returned object can also come from a
parameter or from a call to another method.
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:
Reserved
public class RollingDie
{
private static final double slowDown = 0.97;
private static final double speedFactor = 0.04;
...
words:
static
final
• 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)
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;
OK
statMethod2(...);
instVar = ...;
instMethod(...);
}
Errors!
Static
method
Static Methods (cont’d)
• main is static and therefore cannot access
non-static fields or call non-static methods
of its class:
Error:
public class Hello
{
private int test () { ... }
public static void main (String[ ] args)
{
System.out.println (test ());
}
}
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(...);
vendor.addMoney(25);
die1.roll();
• Non-static methods can access all fields and
call all methods of their class — both static
and non-static.
Inheritance
• In OOP a programmer can create a new
class by extending an existing class
Superclass
(Base class)
subclass extends
superclass
Subclass
(Derived class)
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);
}
Constructor
Calls Walker’s constructor using super
public void turnAround ()
{
Foot lf = getLeftFoot ();
Foot rf = getRightFoot ();
lf.turn (180);
Calls Walker’s accessor methods
rf.turn (180);
lf.moveSideways (-PIXELS_PER_INCH * 8);
rf.moveSideways (PIXELS_PER_INCH * 8);
}
}
A new
method
public class Slowpoke extends Walker
{
...
public int distanceTraveled()
{
return super.distanceTraveled ( ) / 10;
}
...
}
public class Walker
{
...
public int distanceTraveled()
{
return stepsCount * stepLength;
}
...
Calls superclass’s
}
distanceTraveled method
Overrides Walker’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
Superclass
(Base class)
Subclass extends
Superclass
Subclass
(Derived class)
• Inheritance represents the IS-A relationship
between objects: an object of a subclass IS-A(n)
object of the superclass.
Class Hierarchies
• Using inheritance, a programmer can define
a hierarchy of classes.
Biped
Walker
ToedInWalker
Hopper
CharlieChaplin
Dancer
Class Hierarchies (cont’d)
• Help reduce duplication
of code by factoring out
common code from
similar classes into a
common superclass.
Walker
Constructor
firstStep
nextStep
stop
distanceTraveled
Biped
Constructor
Accessors
turnLeft
turnRight
turnAround
draw
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)
{
Works for either
Walker or Hopper
due to polymorphism
creature.firstStep();
while (creature.distanceTraveled() < distance)
creature.nextStep();
public void moveAcross
creature.stop();
}
(Biped creature, int distance)
{
public void moveAcross
creature.firstStep();
while (creature.distanceTraveled() < distance)
(Hopper creature, int distance)
creature.nextStep();
{
creature.stop();
creature.firstStep();
while (creature.distanceTraveled() < distance) }
creature.nextStep();
creature.stop();
}
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)
The actual parameter passed to this
method can be a Walker, a Hopper,
etc.  any subclass of Biped.
public void moveAcross (Biped creature, int distance)
{
creature.firstStep();
while (creature.distanceTraveled () < distance)
creature.nextStep();
creature.stop();
}
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
...
...
...
JTextComponent
Container
JComponent
AbstractButton
JTextArea JTextField ... JMenuItem
Window
JPanel
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)
Methods
• Object is a concrete class
public class Object
{
public String toString {...}
public boolean equals (Object other) {... }
public int hashCode() { ... }
// a few other methods
...
}
redefined
(overridden)
as necessary
Calling Superclass’s
Constructors
Biped
Walker
public class Walker extends Biped
{
// Constructor
public Walker(int x, int y, Image leftPic, Image rightPic)
{
Calls Biped’s
super(x, y, leftPic, rightPic);
...
constructor
}
The number / types of parameters passed to
}
super must match parameters of one of the
If present, must be
the first statement
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.
Object
super( )
Biped
super(...)
Walker
Calling Superclass’s
Methods
Walker
CharlieChaplin
public class CharlieChaplin
extends Walker
{
...
public void nextStep ()
{
turnFeetIn();
Calls Walker’s
super.nextStep();
nextStep
turnFeetOut();
}
...
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
Aerobics
Interface
Dance
Waltz
Rumba
Band
Cha-Cha-Cha
Dancer
Salsa
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 interface Dance
{
DanceStep getStep (int i);
int getTempo ();
int getBeat (int i);
}
• “public abstract” is not written because all
the methods are public abstract.
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.
Dance d = new Waltz( );
• Polymorphism fully applies to objects disguised as
interface types.
Interfaces (cont’d)
public interface Edible
{
String getFoodGroup();
int getCaloriesPerServing();
}
public class Pancake
implements Edible
{
...
}
public class Breakfast
Polymorphism:
{
the correct
private int myTotalCalories = 0;
method is called
...
for any specific
public void eat (Edible obj, int servings)
type of Edible,
{
e.g., a Pancake
myTotalCalories +=
obj.getCaloriesPerServing () * servings;
}
...
}
Classes
Interfaces
Similarities
• A superclass provides a
secondary data type to
objects of its subclasses.
• An interface provides a
secondary data type to
objects of classes that
implement that interface.
• An abstract class cannot
be instantiated.
• An interface cannot be
instantiated.
Classes
Interfaces
Similarities
• 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.
Classes
Interfaces
Differences
• 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.
Classes
Interfaces
Differences
• A concrete class has all its
methods defined. An
abstract class usually has
one or more abstract
methods.
• All methods declared in an
interface are abstract.
• Every class is a part of a
hierarchy of classes with
Object at the top.
• An interface may belong
to a small hierarchy of
interfaces, but this is not
as common.
OOP Benefits
• Facilitates team development
• Easier to reuse software components and write
reusable software
• Easier GUI (Graphical User Interface) and
multimedia programming