SlideShare a Scribd company logo
1 of 44
Download to read offline
Connect. Collaborate. Innovate.




                                  Object Oriented
                               Programming with Java



                                   Learning Facilitator:
                                          Date:




© Copyright GlobalLogic 2009                                               1
Connect. Collaborate. Innovate.




                               Gentle Reminder:
                   “Switch Off” your Mobile Phone
                                 Or
                 Switch Mobile Phone to “Silent Mode”




© Copyright GlobalLogic 2009                                            2
Agenda                         Connect. Collaborate. Innovate.




• Introduction to OOPS

• OOPS in Java
        –    Classes
        –    Objects
        –    Inheritance
        –    Polymorphism
        –    Encapsulation




© Copyright GlobalLogic 2009                              3
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
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
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
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
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
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
Exercise :                                  Connect. Collaborate. Innovate.




• Create a Customer class, instantiate it




© Copyright GlobalLogic 2009                                           10
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
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
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
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
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
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
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
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
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
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
Exercise                                            Connect. Collaborate. Innovate.




• Light – TubeLight inheritance example
• Demonstrate Dynamic binding of instance methods




© Copyright GlobalLogic 2009                                                   21
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
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
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
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
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
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
Connect. Collaborate. Innovate.
               public accessibility




© Copyright GlobalLogic 2009                                     28
Connect. Collaborate. Innovate.
               protected accessibility




© Copyright GlobalLogic 2009                                        29
Connect. Collaborate. Innovate.
               default accessibility




© Copyright GlobalLogic 2009                                      30
Connect. Collaborate. Innovate.
               private accessibility




© Copyright GlobalLogic 2009                                      31
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
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
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
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
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
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
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
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
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
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
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
Connect. Collaborate. Innovate.




                               Q&A


© Copyright GlobalLogic 2009                                           43
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

More Related Content

What's hot

Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Theo Jungeblut
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetdevlabsalliance
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questionsRohit Singh
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questionsppratik86
 
Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Designtheamiableapi
 
Extreme Interview Questions
Extreme Interview QuestionsExtreme Interview Questions
Extreme Interview QuestionsEhtisham Ali
 
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)Theo Jungeblut
 
Overcoming The Impedance Mismatch Between Source Code And Architecture
Overcoming The Impedance Mismatch Between Source Code And ArchitectureOvercoming The Impedance Mismatch Between Source Code And Architecture
Overcoming The Impedance Mismatch Between Source Code And ArchitecturePeter Friese
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategiesthirumuru2012
 
Jazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipseJazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipsePeter Friese
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4mlrbrown
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)smumbahelp
 
Java session08
Java session08Java session08
Java session08Niit Care
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Eclipse Democamp Zurich
Eclipse Democamp ZurichEclipse Democamp Zurich
Eclipse Democamp ZurichMarcel Bruch
 

What's hot (19)

Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
 
Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Design
 
Extreme Interview Questions
Extreme Interview QuestionsExtreme Interview Questions
Extreme Interview Questions
 
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
 
Overcoming The Impedance Mismatch Between Source Code And Architecture
Overcoming The Impedance Mismatch Between Source Code And ArchitectureOvercoming The Impedance Mismatch Between Source Code And Architecture
Overcoming The Impedance Mismatch Between Source Code And Architecture
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
 
Jazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipseJazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with Eclipse
 
hibernate
hibernatehibernate
hibernate
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
Java session08
Java session08Java session08
Java session08
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Oop Article Jan 08
Oop Article Jan 08Oop Article Jan 08
Oop Article Jan 08
 
Eclipse Democamp Zurich
Eclipse Democamp ZurichEclipse Democamp Zurich
Eclipse Democamp Zurich
 

Similar to Oops

Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsPragya Rastogi
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java LanguagePawanMM
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVPHarshith Keni
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptxmadan r
 
Reverse engineering
Reverse engineeringReverse engineering
Reverse engineeringSaswat Padhi
 
Intro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-CIntro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-CAndrew Rohn
 
programacion orientado a abjetos poo
programacion orientado a abjetos pooprogramacion orientado a abjetos poo
programacion orientado a abjetos pooRasec De La Cruz
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSergey Aganezov
 
Lesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptxLesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptxLuiFlor
 
Eclipse Training - Introduction
Eclipse Training - IntroductionEclipse Training - Introduction
Eclipse Training - IntroductionLuca D'Onofrio
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptBill Buchan
 

Similar to Oops (20)

Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Modularization in java 8
Modularization in java 8Modularization in java 8
Modularization in java 8
 
Solid OOPS
Solid OOPSSolid OOPS
Solid OOPS
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVP
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptx
 
oop Lecture 10
oop Lecture 10oop Lecture 10
oop Lecture 10
 
Reverse engineering
Reverse engineeringReverse engineering
Reverse engineering
 
Intro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-CIntro to iOS: Object Oriented Programming and Objective-C
Intro to iOS: Object Oriented Programming and Objective-C
 
programacion orientado a abjetos poo
programacion orientado a abjetos pooprogramacion orientado a abjetos poo
programacion orientado a abjetos poo
 
Shuzworld Analysis
Shuzworld AnalysisShuzworld Analysis
Shuzworld Analysis
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
Eclipse Vs Netbeans
Eclipse Vs NetbeansEclipse Vs Netbeans
Eclipse Vs Netbeans
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
 
Lesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptxLesson 1 - Object Oriented Programming CPP103.pptx
Lesson 1 - Object Oriented Programming CPP103.pptx
 
Eclipse Training - Introduction
Eclipse Training - IntroductionEclipse Training - Introduction
Eclipse Training - Introduction
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in Lotuscript
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 

More from Pragya Rastogi (20)

Gl android platform
Gl android platformGl android platform
Gl android platform
 
Qtp questions
Qtp questionsQtp questions
Qtp questions
 
Qtp not just for gui anymore
Qtp   not just for gui anymoreQtp   not just for gui anymore
Qtp not just for gui anymore
 
Qtp tutorial
Qtp tutorialQtp tutorial
Qtp tutorial
 
Qtp4 bpt
Qtp4 bptQtp4 bpt
Qtp4 bpt
 
Get ro property outputting value
Get ro property outputting valueGet ro property outputting value
Get ro property outputting value
 
Bp ttutorial
Bp ttutorialBp ttutorial
Bp ttutorial
 
Gl istqb testing fundamentals
Gl istqb testing fundamentalsGl istqb testing fundamentals
Gl istqb testing fundamentals
 
Gl scrum testing_models
Gl scrum testing_modelsGl scrum testing_models
Gl scrum testing_models
 
My Sql concepts
My Sql conceptsMy Sql concepts
My Sql concepts
 
70433 Dumps DB
70433 Dumps DB70433 Dumps DB
70433 Dumps DB
 
70 433
70 43370 433
70 433
 
70562-Dumps
70562-Dumps70562-Dumps
70562-Dumps
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
32916
3291632916
32916
 
70 562
70 56270 562
70 562
 
Mobile testingartifacts
Mobile testingartifactsMobile testingartifacts
Mobile testingartifacts
 
GL_Web application testing using selenium
GL_Web application testing using seleniumGL_Web application testing using selenium
GL_Web application testing using selenium
 
Gl qtp day 3 1
Gl qtp day 3   1Gl qtp day 3   1
Gl qtp day 3 1
 
Gl qtp day 1 & 2
Gl qtp   day 1 & 2Gl qtp   day 1 & 2
Gl qtp day 1 & 2
 

Recently uploaded

Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdfJamie (Taka) Wang
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 

Recently uploaded (20)

Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 

Oops

  • 1. Connect. Collaborate. Innovate. Object Oriented Programming with Java Learning Facilitator: Date: © Copyright GlobalLogic 2009 1
  • 2. Connect. Collaborate. Innovate. Gentle Reminder: “Switch Off” your Mobile Phone Or Switch Mobile Phone to “Silent Mode” © Copyright GlobalLogic 2009 2
  • 3. Agenda Connect. Collaborate. Innovate. • Introduction to OOPS • OOPS in Java – Classes – Objects – Inheritance – Polymorphism – Encapsulation © Copyright GlobalLogic 2009 3
  • 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. 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. 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. 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. 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. 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. Exercise : Connect. Collaborate. Innovate. • Create a Customer class, instantiate it © Copyright GlobalLogic 2009 10
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Exercise Connect. Collaborate. Innovate. • Light – TubeLight inheritance example • Demonstrate Dynamic binding of instance methods © Copyright GlobalLogic 2009 21
  • 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. 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. 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. 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. 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. 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. Connect. Collaborate. Innovate. public accessibility © Copyright GlobalLogic 2009 28
  • 29. Connect. Collaborate. Innovate. protected accessibility © Copyright GlobalLogic 2009 29
  • 30. Connect. Collaborate. Innovate. default accessibility © Copyright GlobalLogic 2009 30
  • 31. Connect. Collaborate. Innovate. private accessibility © Copyright GlobalLogic 2009 31
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Connect. Collaborate. Innovate. Q&A © Copyright GlobalLogic 2009 43
  • 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