Oops

611 views
540 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
611
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
36
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Oops

  1. 1. Connect. Collaborate. Innovate. Object Oriented Programming with Java Learning Facilitator: Date:© Copyright GlobalLogic 2009 1
  2. 2. Connect. Collaborate. Innovate. Gentle Reminder: “Switch Off” your Mobile Phone Or Switch Mobile Phone to “Silent Mode”© Copyright GlobalLogic 2009 2
  3. 3. Agenda Connect. Collaborate. Innovate.• Introduction to OOPS• OOPS in Java – Classes – Objects – Inheritance – Polymorphism – Encapsulation© Copyright GlobalLogic 2009 3
  4. 4. Introduction to OOPS Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 4
  5. 5. Introduction to OOPS Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 5
  6. 6. OOPS in Java: Class Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 6
  7. 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); } }© Copyright GlobalLogic 2009 7
  8. 8. OOPS in Java: Object Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 8
  9. 9. Connect. Collaborate. Innovate. OOPS in Java: Object • A simple example which uses objects: 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(); } } • Output: Id: 0, Department: null© Copyright GlobalLogic 2009 9
  10. 10. Exercise : Connect. Collaborate. Innovate.• Create a Customer class, instantiate it© Copyright GlobalLogic 2009 10
  11. 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); } }© Copyright GlobalLogic 2009 11
  12. 12. Connect. Collaborate. Innovate. OOPS in Java: Object : Constructors • An example which demonstrates constructor usage: 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(); } } • Output: Id: 1, Department: IT Id: 2, Department: HR© Copyright GlobalLogic 2009 12
  13. 13. Exercise Connect. Collaborate. Innovate.• Add constructors to the Customer class.• Use this keyword to avoid parameter name mismatch• Add a static field - customerCount© Copyright GlobalLogic 2009 13
  14. 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. } }© Copyright GlobalLogic 2009 14
  15. 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© Copyright GlobalLogic 2009 15
  16. 16. OOPS in Java: Inheritance Connect. Collaborate. Innovate.• 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).© Copyright GlobalLogic 2009 16
  17. 17. OOPS in Java: Inheritance Connect. Collaborate. Innovate.• 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 super keyword. • 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.© Copyright GlobalLogic 2009 17
  18. 18. OOPS in Java: Inheritance Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 18
  19. 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”); } }© Copyright GlobalLogic 2009 19
  20. 20. Connect. Collaborate. Innovate. OOPS in Java: Inheritance • An example which demonstrates inheritance: 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(); } } • Output: Id: 1, Department: IT Id: 2, Department: HR Id: 3, Department: MGR Managing 2 employees© Copyright GlobalLogic 2009 20
  21. 21. Exercise Connect. Collaborate. Innovate.• Light – TubeLight inheritance example• Demonstrate Dynamic binding of instance methods© Copyright GlobalLogic 2009 21
  22. 22. OOPS in Java: Encapsulation Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 22
  23. 23. OOPS in Java: Encapsulation Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 23
  24. 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 + “)”); } }© Copyright GlobalLogic 2009 24
  25. 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] + “)”); } }© Copyright GlobalLogic 2009 25
  26. 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() + “)”); } }© Copyright GlobalLogic 2009 26
  27. 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() + “)”); } }© Copyright GlobalLogic 2009 27
  28. 28. Connect. Collaborate. Innovate. public accessibility© Copyright GlobalLogic 2009 28
  29. 29. Connect. Collaborate. Innovate. protected accessibility© Copyright GlobalLogic 2009 29
  30. 30. Connect. Collaborate. Innovate. default accessibility© Copyright GlobalLogic 2009 30
  31. 31. Connect. Collaborate. Innovate. private accessibility© Copyright GlobalLogic 2009 31
  32. 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(); } }© Copyright GlobalLogic 2009 32
  33. 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(); } }© Copyright GlobalLogic 2009 33
  34. 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(); } }© Copyright GlobalLogic 2009 34
  35. 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(); } }© Copyright GlobalLogic 2009 35
  36. 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(); } }© Copyright GlobalLogic 2009 36
  37. 37. OOPS in Java: Polymorphism Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 37
  38. 38. OOPS in Java: Polymorphism Connect. Collaborate. Innovate.• 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.© Copyright GlobalLogic 2009 38
  39. 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;} }© Copyright GlobalLogic 2009 39
  40. 40. Connect. Collaborate. Innovate. OOPS in Java: Polymorphism 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))); } } • Output: 25 12© Copyright GlobalLogic 2009 40
  41. 41. Exercise Connect. Collaborate. Innovate.• Demonstrate method overloading in Customer class. Overload the puchaseProduct() method, allowing products to be purchased by ID (long) or Key(String)© Copyright GlobalLogic 2009 41
  42. 42. Operator Overloading Connect. Collaborate. Innovate. – 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).© Copyright GlobalLogic 2009 42
  43. 43. Connect. Collaborate. Innovate. Q&A© Copyright GlobalLogic 2009 43
  44. 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: learning@globallogic.com© Copyright GlobalLogic 2009 44

×