Oops

44
© Copyright GlobalLogic 2009 1 Connect. Collaborate. Innovate. Object Oriented Programming with Java Learning Facilitator: Date:

description

 

Transcript of Oops

Page 1: Oops

© Copyright GlobalLogic 2009 1

Connect. Collaborate. Innovate.

Object Oriented

Programming with Java

Learning Facilitator:

Date:

Page 2: Oops

© Copyright GlobalLogic 2009 2

Connect. Collaborate. Innovate.

Gentle Reminder:

“Switch Off” your Mobile Phone

Or

Switch Mobile Phone to “Silent Mode”

Page 3: Oops

© Copyright GlobalLogic 2009 3

Connect. Collaborate. Innovate.Agenda

• Introduction to OOPS

• OOPS in Java

– Classes

– Objects

– Inheritance

– Polymorphism

– Encapsulation

Page 4: Oops

© Copyright GlobalLogic 2009 4

Connect. Collaborate. Innovate.Introduction to OOPS

• Procedural programming: The traditional view where a program is seen as simply a series of computational steps to be executed.

• Suitable for moderately complex programs, but led to quality, maintainability and readability issues as software became increasingly complex.

• Object-oriented programming (OOP) attempts to solve this problem by modularizing software into a collection of cooperating objects.

Page 5: Oops

© Copyright GlobalLogic 2009 5

Connect. Collaborate. Innovate.Introduction to OOPS

• Each object maintains state and exposes related behavior, and can be viewed as an independent module with a distinct responsibility.

• OOPS is popular in large-scale software engineering, since it promotes greater flexibility, maintainability, ease of development and better readability by virtue of its emphasis on modularity.

• Java, C++, Visual Basic .NET, C#, etc. are popular object-oriented programming languages.

Page 6: Oops

© Copyright GlobalLogic 2009 6

Connect. Collaborate. Innovate.OOPS in Java: Class

• A class is the blueprint from which individual objects are created.

• A class addresses the following questions about any object created from it:

– What possible states can the object be in?

– What possible behavior can the object perform?

• A class defines state in the form of fields, and exposes behavior through methods.

• Collectively, the fields and methods defined by a class are called members of the class.

Page 7: Oops

© Copyright GlobalLogic 2009 7

Connect. Collaborate. Innovate.

OOPS in Java: Class

• A simple class:

public class Employee {

// Field definitions for storing state

private int id;

private String department;

// Method definitions for exposing behavior

public void printDetails() {

System.out.println(“Id: ” + id + “, Department: ” + department);

}

}

Page 8: Oops

© Copyright GlobalLogic 2009 8

Connect. Collaborate. Innovate.OOPS in Java: Object

• An object is a particular instance of a class.

• In Java, objects are created from classes using constructors.

• A constructor is a special method having the same name as that of the class and no return type. A constructor can accept parameters or arguments like a normal method.

• A constructor usually contains the logic for suitably initializing the state of the object being created.

• If no constructor is defined for a class, Java provides a default no-argument constructor which initializes primitive fields to their default values and reference fields to null.

Page 9: Oops

© Copyright GlobalLogic 2009 9

Connect. Collaborate. Innovate.

OOPS in Java: Object

• A simple example which uses objects:

• Output:

public class EmployeeTest {

public static void main(String [ ] args) {

// Use the default no-argument constructor

// for creating a new instance of Employee

Employee e = new Employee();

e.printDetails();

}

}

Id: 0, Department: null

Page 10: Oops

© Copyright GlobalLogic 2009 10

Connect. Collaborate. Innovate.Exercise :

• Create a Customer class, instantiate it

Page 11: Oops

© Copyright GlobalLogic 2009 11

Connect. Collaborate. Innovate.

OOPS in Java: Object : Constructors

• The employee class with a constructor:

public class Employee {

// Field definitions for storing state

private int id;

private String department;

// Constructor

public Employee(int inId, String inDept) {

id = inId;

department = inDept;

}

// Method definitions for exposing behavior

public void printDetails() {

System.out.println(“Id: ” + id + “, Department: ” + department);

}

}

Page 12: Oops

© Copyright GlobalLogic 2009 12

Connect. Collaborate. Innovate.

OOPS in Java: Object : Constructors

• An example which demonstrates constructor usage:

• Output:

public class EmployeeTest {

public static void main(String [ ] args) {

// Use defined constructor

Employee e1 = new Employee(1, “IT”);

Employee e2 = new Employee(2, “HR”);

e1.printDetails();

e2.printDetails();

}

}

Id: 1, Department: IT

Id: 2, Department: HR

Page 13: Oops

© Copyright GlobalLogic 2009 13

Connect. Collaborate. Innovate.Exercise

• Add constructors to the Customer class.

• Use this keyword to avoid parameter name mismatch

• Add a static field - customerCount

Page 14: Oops

© Copyright GlobalLogic 2009 14

Connect. Collaborate. Innovate.

A Must Know …

• PARAMETER PASSING

By reference / by value ???

// Primitive Data Types

class PizzaFactory {

public double calcPrice(int numberOfPizzas, double pizzaPrice) {

pizzaPrice = pizzaPrice/2.0; // Change price.

return numberOfPizzas * pizzaPrice;

}

}

public class CustomerOne {

public static void main (String[] args) {

PizzaFactory pizzaHouse = new PizzaFactory();

int pricePrPizza = 15;

double totPrice = pizzaHouse.calcPrice(4, pricePrPizza);

System.out.println("Value of pricePrPizza: " + pricePrPizza); // Unchanged.

}

}

Page 15: Oops

© Copyright GlobalLogic 2009 15

Connect. Collaborate. Innovate.

A Must Know …

//Object Reference Values

public class CustomerTwo {

public static void main (String[] args) {

Pizza favoritePizza = new Pizza();

System.out.println("Meat on pizza before baking: " + favoritePizza.meat);

bake(favoritePizza);

System.out.println("Meat on pizza after baking: " + favoritePizza.meat);

}

public static void bake(Pizza pizzaToBeBaked) { pizzaToBeBaked.meat = "chicken"; // Change the meat

pizzaToBeBaked = null; // (4)

}

}

class Pizza { // (5)

String meat = "beef";

}

OUTPUT :

Meat on pizza before baking: beef

Meat on pizza after baking: chicken

Page 16: Oops

© Copyright GlobalLogic 2009 16

Connect. Collaborate. Innovate.OOPS in Java: Inheritance

• Inheritance is a way to form new classes (called derived- or sub-classes) from existing classes (called base- or super-classes).

• Subclasses inherit attributes and behavior from their base classes, and can introduce their own. Defines is-a relationship

• Promotes code reuse.

• Java supports single inheritance, i.e. a subclass can inherit from only one superclass.

• The java.lang.Object class is the root of the inheritance hierarchy. If a class is not explicitly declared to inherit from a base class, it is implicitly assumed to inherit from java.lang.Object.

• A subclass can always be implicitly cast to its superclass (or any other ancestor class further up the inheritance hierarchy).

Page 17: Oops

© Copyright GlobalLogic 2009 17

Connect. Collaborate. Innovate.OOPS in Java: Inheritance

• Aspects of inheritance:

– Specialization: A subclass can have new state or behavior aspects which are not part of the base class, i.e. a subclass may define new fields and methods.

– Overriding: A subclass can alter its inherited traits by defining a method with the same name and parameter types as an inherited method. The inherited method is said to have been overridden in the subclass.

• The overriding method may reference the overridden method by using the superkeyword.

• Final methods and methods in final classes cannot be overridden.

• Java uses dynamic binding for handling method overriding, i.e. the JVM decides at runtime which method implementation to invoke based on the actual (not declared) class of the object on which the method is being invoked.

Page 18: Oops

© Copyright GlobalLogic 2009 18

Connect. Collaborate. Innovate.OOPS in Java: Inheritance

• Constructors and inheritance:

– A subclass constructor may reference a superclass constructor by using the super keyword.

– The call to the superclass constructor (if present) should always be the first statement in the subclass constructor.

– If the subclass constructor does not explicitly call a superclass constructor in its first statement, Java automatically inserts a call to the no-argument superclass constructor at the beginning of the subclass constructor.

Page 19: Oops

© Copyright GlobalLogic 2009 19

Connect. Collaborate. Innovate.

OOPS in Java: Inheritance

• An example of inheritance:

// The „extends‟ keyword is used to denote that Manager inherits from Employee

public class Manager extends Employee {

// Specialization, addition of a new team field.

private Employee [ ] team;

public Manager(int inId, String inDept, Employee [ ] inTeam) {

// Call to superclass constructor in first statement

super(inId, inDept);

team = inTeam;

}

// Overriding

public void printDetails() {

// Call overridden method.

super.printDetails();

System.out.println(“\tManaging ” + team.length + “ employees”);

}

}

Page 20: Oops

© Copyright GlobalLogic 2009 20

Connect. Collaborate. Innovate.

OOPS in Java: Inheritance

• An example which demonstrates inheritance:

• Output:

public class EmployeeTest {

public static void main(String [ ] args) {

Employee e1 = new Employee(1, “IT”);

Employee e2 = new Employee(2, “HR”);

// An instance of the Manager class can be implicitly cast

// to its superclass Employee

Employee m = new Manager(3, “MGR”, new Employee [ ] {e1, e2});

e1.printDetails();

e2.printDetails();

// Dynamic binding kicks in here. Even though the declared type

// of m is Employee, the printDetails() which gets invoked is the

// one overridden in Manager, since m is actually an instance of Manager.

m.printDetails();

}

}

Id: 1, Department: IT

Id: 2, Department: HR

Id: 3, Department: MGR

Managing 2 employees

Page 21: Oops

© Copyright GlobalLogic 2009 21

Connect. Collaborate. Innovate.Exercise

• Light – TubeLight inheritance example

• Demonstrate Dynamic binding of instance methods

Page 22: Oops

© Copyright GlobalLogic 2009 22

Connect. Collaborate. Innovate.OOPS in Java: Encapsulation

• Encapsulation conceals the exact details of how a particular class works from objects that use the class.

• Hides design decisions in a class that are most likely to change, thus protecting other dependent classes from change if the design decision is changed.

• Achieved by specifying which classes may use the members of an object.

Page 23: Oops

© Copyright GlobalLogic 2009 23

Connect. Collaborate. Innovate.OOPS in Java: Encapsulation

• Modifiers provided by Java for facilitating encapsulation:

– public: The member is available to all classes.

– protected: The member is available to the defining class, sub-classes and classes in the same package.

– private: The member is available only to the defining class.

– Default or package (no modifier): The member is available to the defining class and classes in the same package.

Page 24: Oops

© Copyright GlobalLogic 2009 24

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

• An example which illustrates the use of encapsulation:

// Point class containing x and y coordinates

// Bad implementation, the mechanism used for storing the

// coordinates (instance variables x and y) is exposed to other classes.

// Further, direct manipulation of x and y is the only way other

// classes can store/retrieve coordinates.

public class Point {

public int x;

public int y;

}

public class PointTest {

private Point getPoint() {

Point p = new Point();

p.x = 3;

p.y = 4;

return p;

}

public void testPoint() {

Point p = getPoint();

System.out.println(“(” + p.x + “, “ + p.y + “)”);

}

}

Page 25: Oops

© Copyright GlobalLogic 2009 25

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

• For whatever reasons, the Point implementation now has to be changed to store coordinates in an array instead of individual fields:

public class Point {

// c[0] = x, c[1] = y

public int [ ] c;

}

public class PointTest {

private Point getPoint() {

Point p = new Point();

// Bad, must also change logic here…

p.c = new int [ ] {3, 4};

return p;

}

public void testPoint() {

Point p = getPoint();

// Bad, must also change logic here…

System.out.println(“(” + p.c[0] + “, “ + p.c[1] + “)”);

}

}

Page 26: Oops

© Copyright GlobalLogic 2009 26

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

• A better implementation of Point:

// The coordinate storage mechanism is now hidden from other classes (x and y are private).

// Coordinates can be stored/retrieved only through public methods, whose internal logic

// can be changed later if the coordinate storage mechanism changes, without affecting other

// classes using these methods.

public class Point {

private int x, y;

public void setX(int inX) {x = inX;}

public int getX() {return x;}

public void setY(int inY) {y = inY;}

public int getY() {return y;}

}

public class PointTest {

private Point getPoint() {

Point p = new Point();

p.setX(3);

p.setY(4);

return p;

}

public void testPoint() {

Point p = getPoint();

System.out.println(“(” + p.getX() + “, “ + p.getY() + “)”);

}

}

Page 27: Oops

© Copyright GlobalLogic 2009 27

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

• Let’s now change the storage mechanism used by Point:

public class Point {

private int [] c;

public Point() {c = new int [2];}

public void setX(int inX) {c[0] = inX;}

public int getX() {return c[0];}

public void setY(int inY) {c[1] = inY;}

public int getY() {return c[1];}

}

// No change in PointTest!

public class PointTest {

private Point getPoint() {

Point p = new Point();

p.setX(3);

p.setY(4);

return p;

}

public void testPoint() {

Point p = getPoint();

System.out.println(“(” + p.getX() + “, “ + p.getY() + “)”);

}

}

Page 28: Oops

© Copyright GlobalLogic 2009 28

Connect. Collaborate. Innovate.

public accessibility

Page 29: Oops

© Copyright GlobalLogic 2009 29

Connect. Collaborate. Innovate.

protected accessibility

Page 30: Oops

© Copyright GlobalLogic 2009 30

Connect. Collaborate. Innovate.

default accessibility

Page 31: Oops

© Copyright GlobalLogic 2009 31

Connect. Collaborate. Innovate.

private accessibility

Page 32: Oops

© Copyright GlobalLogic 2009 32

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

• An example which illustrates encapsulation related modifiers:

package a;

public class A {

private void aPriv() {}

void aDef() {}

protected void aProt() {}

public void aPub() {}

public void aTest() {

// OK, private members are accessible to defining class

aPriv();

// OK, package private members are accessible to defining class

aDef();

// OK, protected members are accessible to defining class

aProt();

// OK, public members are accessible to all classes

aPub();

}

}

Page 33: Oops

© Copyright GlobalLogic 2009 33

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

package a;

public class AExt1 extends A {

public void aExt1Test() {

// Not OK, private members are not accessible outside

// defining class. Will throw compilation error.

aPriv();

// OK, package private members are accessible to other classes

// in the same package.

aDef();

// OK, protected members are accessible to subclasses.

aProt();

// OK, public members are accessible to all classes

aPub();

}

}

Page 34: Oops

© Copyright GlobalLogic 2009 34

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

package b;

import a.A;

public class AExt2 extends A {

public void aExt2Test() {

// Not OK, private members are not accessible outside

// defining class. Will throw compilation error.

aPriv();

// Not OK, package private members are not accessible to

// classes in a different package. Will throw compilation error.

aDef();

// OK, protected members are accessible to subclasses.

aProt();

// OK, public members are accessible to all classes

aPub();

}

}

Page 35: Oops

© Copyright GlobalLogic 2009 35

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

package a;

public class AA {

public void aaTest() {

A a = new A();

// Not OK, private members are not accessible outside

// defining class. Will throw compilation error.

a.aPriv();

// OK, package default members are accessible to other classes

// in the same package.

a.aDef();

// OK, protected members are accessible to other classes in

// the same package.

a.aProt();

// OK, public members are accessible to all classes

a.aPub();

}

}

Page 36: Oops

© Copyright GlobalLogic 2009 36

Connect. Collaborate. Innovate.

OOPS in Java: Encapsulation

package b;

import a.A;

public class B {

public void bTest() {

A a = new A();

// Not OK, private members are not accessible outside

// defining class. Will throw compilation error.

a.aPriv();

// Not OK, package private members are not accessible to

// classes in a different package. Will throw compilation error.

a.aDef();

// Not OK, B is neither a subclass of A nor in the same

// package. Will throw compilation error.

a.aProt();

// OK, public members are accessible to all classes

a.aPub();

}

}

Page 37: Oops

© Copyright GlobalLogic 2009 37

Connect. Collaborate. Innovate.OOPS in Java: Polymorphism

• The capability of an operator or method to do different things based on the object(s) that it is acting upon.

• Aspects:

– Overriding polymorphism

– Overloading polymorphism

• Overriding polymorphism:

– Already discussed in section on inheritance.

– See Employee-Manager example, the printDetails() method produces a different output depending on the runtime class (Employee or Manager) of the object it is invoked on.

Page 38: Oops

© Copyright GlobalLogic 2009 38

Connect. Collaborate. Innovate.OOPS in Java: Polymorphism

• Overloading polymorphism:

– Method overloading:

• The ability to define multiple methods with the same name but different parameter lists.

• Allows the programmer to define how to perform the same action on different types of inputs.

Page 39: Oops

© Copyright GlobalLogic 2009 39

Connect. Collaborate. Innovate.

OOPS in Java: Polymorphism

• Example which illustrates method overloading:

public class Square extends Quadrilateral {

private int side;

public Square(int inSide) {side = inSide;}

public int getSide() {return side;}

}

public class Rectangle extends Quadrilateral {

private int width;

private int height;

public Rectangle(int inWidth, int inHeight) {

width = inWidth;

height = inHeight;

}

public int getWidth() {return width;}

public int getHeight() {return height;}

}

Page 40: Oops

© Copyright GlobalLogic 2009 40

Connect. Collaborate. Innovate.

OOPS in Java: Polymorphism

• Output:

public class AreaCalculator {

// „computeArea‟ is overloaded for Square and Rectangle

private int computeArea(Square s) {return s.getSide() * s.getSide();}

private int computeArea(Rectangle r) {return r.getWidth() * r.getHeight();}

public static void main(String [] args) {

// This call goes to computeArea(Square)

System.out.println(computeArea(new Square(5)));

// This call goes to computeArea(Rectangle)

System.out.println(computeArea(new Rectangle(3, 4)));

}

}

25

12

Page 41: Oops

© Copyright GlobalLogic 2009 41

Connect. Collaborate. Innovate.Exercise

• Demonstrate method overloading in Customer class. Overload the puchaseProduct() method, allowing products to be purchased by ID (long) or Key(String)

Page 42: Oops

© Copyright GlobalLogic 2009 42

Connect. Collaborate. Innovate.Operator Overloading

– Operator overloading

• The ‘+’ operator is a classic example in Java.

• It performs numeric addition or string concatenation depending on whether it’s being invoked on numbers or strings.

• 3 + 4 produces 7 (addition), while “foo” + “bar” produces “foobar” (concatenation).

Page 43: Oops

© Copyright GlobalLogic 2009 43

Connect. Collaborate. Innovate.

Q & A

Page 44: Oops

© Copyright GlobalLogic 2009 44

Connect. Collaborate. Innovate.

“Thank You” for your learning contribution!

Please submit feedback to help L&D make continuous improvement……

Dial @ Learning:Noida: 4444, Nagpur:333, Pune:5222, Banglore:111

E mail: [email protected]