OOP with Java

Post on 03-Jan-2016

35 views 4 download

description

OOP with Java. Course objectives. OOP Introduction Principles of OOP Java OOP. Learning Approach. The following are strongly suggested for a better learning and understanding of this course: Noting down the key concepts in the class Analyze all the examples / code snippets provided - PowerPoint PPT Presentation

transcript

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

OOP with Java

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Course objectives

OOP Introduction Principles of OOP Java OOP

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Learning Approach

The following are strongly suggested for a better learning and understanding of this course: Noting down the key concepts in the class Analyze all the examples / code snippets provided Study and understand the self study topics Completion and submission of all the assignments, on time Completion of the self review questions in the lab guide Study and understand all the artifacts including the reference

materials / e-learning / supplementary materials specified Completion of the project (if application for this course) on time

inclusive of individual and group activities Taking part in the self assessment activities Participation in the doubt clearing sessions

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Session 1: OOP Introduction

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Procedural Programming

Back in the "old days" we had Procedural Programming:Data was separate from code.Programmer is responsible for organizing

everything in to logical units of code/data.No help from the compiler/language for enforcing

modularity, …

It’s hard to build large systems (not impossible, just hard).

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

What is OOP

It stands for Object Oriented Programming. OOP is a design philosophy. OOP is a programming paradigm. It using "objects" – data structures consisting

of data fields and methods together with their interactions – to design applications and computer programs

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Comparison

Procedural Object-oriented

procedure method

module object

procedure call message

variable attribute

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Why OOP?

The objects are the most stable factor in the problem Algorithms may be improved Implementations may be modified Interface may undergo major changes

If the data structure for the objects is defined according to algorithm / implementation / interface it is very likely to backfire when one of them is changed.

Objects are the appropriate level at which decisions about encapsulation (information hiding) are made.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Why OOP?

OOP systems can be easily upgraded from small to large scale.

It is easy to partition the work in a project based on objects.

It reduces software maintenance and developing costs.

Changes in user requirements or later developments have always been a major problem. OOP can be the ultimate solution in this case.

OOP should help in developing high quality software easily.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

OOP will NOT

Design program for you Prevent you from designing a bad program Provide algorithms Perform data management

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Key terms

“object” collection of private data & public operations

“class” description of a set of objects

“instance” an instance of a class is an object in that class

“method” procedure which carries out some operation

“message” request to execute a method (like a procedure call)

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Key Terms (cont.)

With OOP, we model the application domain with objects. An object possesses

Data values or properties Behavioral abilities or methods

Objects with similar attribute and method types comprise sets of objects called classes.

An object which is a member of a class is referred to as an instance of the class.

One object sends a message to another object asking it to do a particular task. The first object does not need to know how the task is done (only how to request that it be done). This corresponds to calling one of the second object’s methods!

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Session 2: Principles of OOP

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

4 major principles of OOP

Encapsulation Abstraction Inheritance Polymorphism

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

1st major principle

Encapsulation

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Implementation and Interface

In OOP, every class has two sides:1. The implementation of the class - the data

structures and code that implement its features. 2. The interface that the class exposes for use by

other classes.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Client

We'll use the word “client” to refer to code that uses the public interface of a class and “implementation” when talking about the guts of a class.

With a good OOP design, the interface is smaller and simpler than the implementation. The public interface exposing only aspects that the clients care about and keeping the details of the implementation hidden away.

Client code will typically allocate objects and send them messages.

With good OOP design, being a client should be easy.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Implementation

Implementation - private, internal How is the object implemented - how does it

organizes its data into instance variables. Methods - what data structures and code to do

the actual implementation. The word "detail" suggests some feature of issue

of the implementation, but which the client does not need to know. It can be kept hidden inside the object - great! When someone says "that's a detail", they mean it's not something the client cares about.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Interface

Interface - public API, external How does the object "expose" its abilities as

public methods for use by client classes. The interface must expose just the issues that are

needed and relevant to the computation - keeping the implementation details hidden as much as possible.

The public interface/API should be organized for the convenience and needs of the clients. A great client interface may look quite different from the underlying implementation.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Example

public class Rectangle {

private String color;

private int width;

private int heigh;

// Constructor

public Rectangle(String c, int w, int h) {

this.setColor(c);

this.setWidth(w);

this.setHeigh(h);

}

private void validateSize() …

private void checkPosition() …

private void setCanvas() …

private void perform() …

Implementation side

Implementation side

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Example

// Draw the rectangle

public String draw() {

// May be some complex code here

this.validateSize();

this.checkPosition();

this.setCanvas();

this.perform();

return "I'm a "

+ this.getColor()

+ " rectangle.";

}

// Calculate perimeter

public int getPerimeter() {

// May be some complex code here

return 2 * (this.getWidth()

+ this.getHeigh());

}

}

Implementation side

Implementation side

Public interface

Public interface

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Example

/*

* Client side code

* Being a client is so easy

*/

Rectangle red = new Rectangle("Red", 5, 8);

// Simple send a message to draw

System.out.println(red.draw());

// Send another message to get perimeter

System.out.println("Perimeter is “ + red.getPerimeter());

Client side

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

2nd major principle

Abstraction

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

What is abstraction

Abstraction is the process by which data and programs are defined with a representation similar to its meaning (semantics), while hiding away the implementation details.

Abstraction tries to reduce and factor out details so that the programmer can focus on a few concepts at a time.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Abstraction

Abstraction is used to manage complexity. Abstraction can apply to control or to data

Control abstraction is the abstraction of actions Data abstraction is the abstraction of data

structures.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Example

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Go abstraction

All Square, Rectangle, Circle and Triangle: Have color Can display

A shape may has all above characteristics, so we call “Shape” is an abstract type of Square, Rectangle, Circle and Triangle.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Abstract - Specific

Shape

Square Rectangle Circle Triangle

More abstract

More specific

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Go abstraction (cont)

Then, we analysis deeper:A rectangle has four sides with lengths w and hA square has all of the characteristics of a

rectangle; in addition, w = h So, square is a type of rectangle, or, rectangle

can be an abstract type of square

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Abstract - Specific

Shape

Square

Rectangle

Circle Triangle

More abstract

More specific

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Go abstraction (cont)

Please answer this question:A circle has center and radiusA dot has all of the characteristics of a circle; in

addition, radius = 0So, which is superclass and which is subclass?

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

3rd major principle

Inheritance

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Inheritance

Ability of a new class to be created, from an existing class by extending it, is called inheritance.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Inheritance Vocabulary

OOP Hierarchy Superclass / Subclass Inheritance Overriding "isa“ - an instance of a subclass isa instance of

the superclass.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

General vs. Specific

The "super" and "sub" terms can be a little counterintuitive:Superclass has fewer properties, is less

constrained, is more general (confusingly, the word "super" can suggests a class with more properties) .

Subclass has more properties, is more constrained, is more specific.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Inheritance Warning

Inheritance is a clever and appealing technology. However, it is best applied in somewhat rare

circumstances - where you have several deeply similar classes.

It is a common error for beginning OOP programmers to try to use inheritance for everything.

In contrast, applications of modularity and encapsulation and API design may be less flashy, but they are incredibly common.

That said, for the cases where inheritance fits, it is a fantastic solution.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Inheritance Example

ShapeColorgetColor()setColor()draw()getPerimeter()getArea()

CircleCenterRadiusgetCenter()setCenter()getRadius()setRadius()draw()getPerimeter()getArea()

RectangleLengthWidthgetLenght()setLenght()getWidth()setWidth()draw()getPerimeter()getArea()

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Inheritance Example

Circle and Rectangle inherit Shape, so Circle and Rectangle has Color property, which is inherited from Shape.

Shape is superclass. Circle and Rectangle are subclasses. Circle isa Shape, but Shape is not a Circle. Method draw() in Circle overriding method

draw() in Shape. If we add/remove property to/from Shape,

then it’s affected to Circle and Rectangle.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

4th major principle

Polymorphism

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Polymorphism

In object-oriented programming, polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning to a particular symbol or "operator" in different contexts.

Polymorphism means one name, many forms.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Polymorphism (cont)

The primary usage of polymorphism in industry is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Polymorphism example

public abstract class Shape {

private String Color;

public Shape(String color) {

this.setColor(color);

}

public String getColor() {

return Color;

}

public void setColor(String color) {

Color = color;

}

abstract public String draw();

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Polymorphism example (cont)

public class Circle extends Shape {

public Circle(String color) {

super(color);

}

@Override

public String draw() {

return "I'm a " + this.getColor() + " circle.";

}

}

public class Rectangle extends Shape {

public Rectangle(String color) {

super(color);

}

@Override

public String draw() {

return "I'm a " + this.getColor() + " rectangle.";

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Polymorphism example (cont)public class PolymorphismExample {

private List<Shape> shapes = new ArrayList<Shape>();

public PolymorphismExample() {

Shape myFirstCircle = new Circle("Red");

Circle mySecondCircle = new Circle("Blue");

Rectangle myFirstRectangle = new Rectangle("Green");

shapes.add(myFirstCircle);

shapes.add(mySecondCircle);

shapes.add(myFirstRectangle);

}

public List<Shape> getShapes() {

return shapes;

}

public static void main(String[] args) {

PolymorphismExample example = new PolymorphismExample();

for (Shape shape : example.getShapes()) {

System.out.println(shape.draw());

}

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Polymorphism example (cont)

Output : I'm a Red circle.

I'm a Blue circle.

I'm a Green rectangle.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Summary

Encapsulation Abstraction Inheritance Polymorphism

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Session 3: Java OOP

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Java OOP

Create new object type with class keyword. A class definition can contain:

variables (fields)initialization codemethods

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Class Definition

class classname {

field declarations

{ initialization code }

Constructors

Methods

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Creating an Object

Defining a class does not create an object of that class - this needs to happen explicitly:

classname varname = new classname();

In general, an object must be created before any methods can be called.the exceptions are static methods.

Sample code: SimpleClass and FooPrinter - FooPrinter can print the strings "FOO" and "foo"

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

FooPrinter.java

public class FooPrinter {

static final String UPPER = "FOO";

static final String LOWER = "foo";

// instance variable, do we print upper or lower?

boolean PrintUpper = false;

void Upper() {

PrintUpper=true;

}

void Lower() {

PrintUpper=false;

}

void Print() {

if (PrintUpper)

System.out.println(UPPER);

else

System.out.println(LOWER);

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

SimpleClass.java

public class SimpleClass{

public static void main(String[] args) {

FooPrinter f = new FooPrinter();

f.Print();

f.Upper();

f.Print();

}

}

Output:

foo

FOO

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

What does it mean to create an object?

An object is a chunk of memory:holds field valuesholds an associated object type

All objects of the same type share codethey all have same object type, but can have

different field values.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Constructors

Very similar to C++ You can create multiple constructors, each

must accept different parameters. If you don't write any constructor, the

compiler will (in effect) write one for you:classname() {}

If you include any constructors in a class, the compiler will not create a default constructor!

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Multiple Constructors

One constructor can call another. You use "this", not the classname:class Foo { int i; Foo() { this(0); } Foo( int x ) { i = x; }

Sample code: ConstructorDemo - demonstration of multiple constructors and using this

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ConstructorDemo.java

//Description: demonstration of multiple constructors and using this.

public class ConstructorDemo {

String objName;

int objNum;

// A constructor that allows the name and num to be set

ConstructorDemo(String s, int i) {

objName = s;

objNum = i;

System.out.println("ConstructorDemo(\"" + s + "\"," + i + ") called");

}

// Default Constructor initializes fields to something

ConstructorDemo() {

this("Default Name", 0);

System.out.println("ConstructorDemo() called");

}

public static void main(String[] args) {

try {

ConstructorDemo d2 = new ConstructorDemo();

ConstructorDemo d1 = new ConstructorDemo(args[0], Integer.parseInt(args[1]));

} catch (Exception e) {

System.out.println("Error: " + e);

}

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Destructors

Nope! There is a finalize() method that is called

when an object is destroyed.You don't have control over when the object is

destroyed (it might never be destroyed).The JVM garbage collector takes care of

destroying objects automatically (you have limited control over this process).

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Class Modifiers

public: that class is visible to all classes everywhere.only one public class per file, must have same

name as the file (this is how Java finds it!). If a class has no modifier (the default, also

known as package-private), it is visible only within its own package.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Abstract Class Modifier

Abstract modifier means that the class can be used as a superclass only.no objects of this class can be created.

Used in inheritance hierarchies…(more on this later).

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Field

Fields (data members) can be any primitive or reference type.As always, declaring a field of a reference type

does not create an object!

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Fields Modifier

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

Access Levels

The following table shows the access to members permitted by each modifier.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Static Fields

Fields declared static are called class fields (class variables).others are called instance fields.

There is only one copy of a static field, no matter how many objects are created.

Sample code: ObjCount - demo of static fields and finalize

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ObjCount.java

public class ObjCount {

// static fields keep track of the next id number

// and the total number of object that exist

static int next_id=0;

static int objcount;

// id is an instance field, each object has it's own.

int id;

public static void main(String[] args) {

int n = Integer.parseInt(args[0]);

for (int i=0;i<n;i++) {

ObjCount o = new ObjCount();

System.out.println(o);

System.out.println("There are " + objcount + " objects ");

if (i % 5 == 0) {

System.gc();

}

}

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ObjCount.java (cont.)

// constructor

ObjCount() {

id = next_id++;

objcount++;

}

// finalize is called when an object is destroyed by the GC

protected void finalize() {

objcount--;

}

public String toString() {

return("ID: " + id );

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Final Fields

The keyword final means: once the value is set, it can never be changed.

Typically used for constants.static final int BUFSIZE=100;

static final double PI=3.14159;

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Method Modifiers

private/protected/public/no modifier: same idea as with fields.

abstract: no implementation given, must be supplied by subclass. the class itself must also be declared abstract

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

• static: the method is a class method, it doesn't depend on any instance fields or methods, and can be called without first creating an object.

• final: the method cannot be changed by a subclass (no alternative implementation can be provided by a subclass).

Method Modifiers

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

• native: the method is written in some local code (C/C++) - the implementation is not provided in Java.

• synchronized: only one thread at a time can call the method.

Method Modifiers

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Method Overloading You can overload methods:

same method name, different parameters.you can't just change return type, the

parameters need to be different. Method overloading is resolved at compile

time.

Won't Work!

int CounterValue() {

return counter;

}

double CounterValue() {

return (double) counter;

}

int CounterValue() {

return counter;

}

double CounterValue() {

return (double) counter;

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Java Inheritance

Two kinds:implementation: the code that defines methods.interface: the method prototypes only.

Other OOP languages often provide the same capabilities (but not as an explicit option).

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Implementation Inheritance

Derived class inherits the implementations of all methods from base class.can replace some with alternatives.new methods in derived class can access all non-

private base class fields and methods.

This is similar to (simple) C++ inheritance.

Sample code: PCInherit - Point and Circle via Inheritance

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

PCInherit.java

class Point {

int x,y;

// constructor - notice we can use this to get past

// the (silly) field name shadowing.

Point( int x, int y) {

this.x = x;

this.y = y;

}

// a method that allows moving the point

void MoveTo(int newx, int newy) {

x = newx; y = newy;

}

// this is called by System.out.println

// (or anything that treats it as a String)

public String toString() {

return(x + "," + y );

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

PCInherit.java (cont.)

// A circle is a special kind of point (inheritance)

class Circle extends Point{

int radius;

Circle( int x, int y, int r) {

// call superclass constructor

super(x,y);

radius = r;

}

public String toString() {

return( "Center: " + super.toString() + " Radius: " + radius);

}

}

// this class is for testing point and circle

public class PCInherit {

public static void main(String[] args) {

Circle c1 = new Circle(10,10,3);

System.out.println(c1);

c1.MoveTo(0,0);

System.out.println(c1);

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Accessing superclass methods from derived class

Can use super keyword to access all (non-private) superclass methods.even those replaced with new versions in the

derived class. Can use super() to call base class constructor.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Single inheritance only(implementation inheritance).

You can't extend more than one class!the derived class can't have more than one base

class. You can do multiple inheritance with interface

inheritance. Cause to avoid the diamond problem.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Casting Objects

A object of a derived class can be cast as an object of the base class.this is much of the power!

When a method is called, the selection of which version of method is run is totally dynamic.overridden methods are dynamic.

Note: Selection of overloaded methods is done at compile time. There are some situations in which this can cause confusion.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

The class Object

Granddaddy of all Java classes.

All methods defined in the class Object are available in every class.

Any object can be cast as an Object.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Interfaces

An interface is a definition of method prototypes and possibly some constants (static final fields).

An interface does not include the implementation of any methods, it just defines a set of methods that could be implemented.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Interface Implementation

A class can implement an interface, this means that it provides implementations for all the methods in the interface.

Java classes can implement any number of interfaces (multiple interface inheritance).

Sample code:ShapeInterface - Interface inheritance with Shape interface

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ShapeInterface.java

// declare the interface

interface Shape {

// every shape needs a draw methods

void Draw();

// every shape needs a print method

void Print();

}

class Square implements Shape {

Point lowerleft;

int sidelen;

// default constructor

Square() {

this(0,0,0);

}

Square(int x, int y, int size) {

lowerleft = new Point(x,y);

sidelen = size;

}

public void Draw() {

System.out.println("Drawing a Square of size " + sidelen + " from " + lowerleft);

}

public void Print() {

System.out.println("Square(" + lowerleft + "," + sidelen+")");

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ShapeInterface.java (cont.)

class Circle implements Shape {

Point center;

int radius;

// default constructor

Circle() {

this(0,0,0);

}

Circle(int x, int y, int size) {

center = new Point(x,y);

radius = size;

}

public void Draw() {

System.out.println("Drawing a Circle of radius “ + radius + " at " + center);

}

public void Print() {

System.out.println("Circle(" + center + "," + radius+")");

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ShapeInterface.java (cont.)

class Point {

int x,y;

// constructor - notice we can use this to get past

// the (silly) field name shadowing.

Point( int x, int y) {

this.x = x;

this.y = y;

}

// a method that allows moving the point

void MoveTo(int newx, int newy) {

x = newx; y = newy;

}

// this is called by System.out.println

// (or anything that treats it as a String)

public String toString() {

return(x + "," + y );

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

ShapeInterface.java (cont.)

// this class is for testing

public class ShapeInterface {

public static void main(String[] args) {

// create some point and circle objects

// we can create and array of Shape objects and put

// them there

Shape [] s = new Shape[6];

int i;

for (i=0; i<3; i++) {

s[i]= new Circle(i,i,i);

}

for (; i<6; i++) {

s[i]= new Square(2*i,i,3*i);

}

// print out the list of shapes

for (i=0; i<s.length; i++) {

s[i].Print();

}

}

}

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Interfaces can be extended

Creation (definition) of interfaces can be done using inheritance:one interface can extend another.

Sometimes interfaces are used just as labeling mechanisms:Look in the Java API documentation for interfaces

like Cloneable.

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Package

A package is a namespace that organizes a set of related classes and interfaces.

Conceptually you can think of packages as being similar to folders on your computer.

Example:java.utilmyproject.common.logging

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Summary

Object Class Interface Field (member) Method Modifier

© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3

Q&A