SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Chapter 04:
Object Oriented Programming
       - Inheritance -
public class Employee {                     public class Part extends Employee {
private String name;                        private float perHour;
                                            private float noOfHours;
public Employee(String
name){this.name=name;}                      public Part(String name, float perHour, float
public Employee(){name="No Name";}          noOfHours){ super(name); this.perHour=perHour;
                                            this.noOfHours=noOfHours;}
public String toString(){return name;}
}                                           public Part(float perHour)
                                            {this.perHour=perHour;}
public class Full extends Employee {        public String toString(){return
private float salary;                       super.toString()+"t"+perHour+"t"+noOfHours;}
                                            public void inrcnoOfHours(float x)
public Full(String name, float salary){     {noOfHours += x;}
super(name);                                public float paid(){return perHour * noOfHours;}}
this.salary=salary;}                             public class Test {
                                                 public static void main(String[] args) {
public Full(float salary){this.salary=salary;}   Full fe1= new Full("Ahmad", 1000f);
                                                 Full fe2= new Full(2000f);
public String toString(){return                  System.out.println(fe1+"n"+fe2);
super.toString()+"t"+salary;}                   Part pe3=new Part("Rami",20f,50f);
public void inrcSalary(float x){salary += x;}    Part pe4=new Part(35f);
}                                                pe3.inrcnoOfHours(50);
                                                 System.out.println(pe3+"n"+pe4);}}
public class Employee{
                                                 private String name;

                                                 public Employee(String
                                                 name){this.name=name;}
                                                 public Employee(){name="No Name";}
public class Full extends Employee {
private float salary;                            public void setName(String
                                                 name){this.name=name;}
public Full(String name, float salary){
  super(name);                                   public String toString(){return name;}
this.salary=salary;}                             {

public Full(float salary){this.salary=salary;}
public void setName(String name){
super.setName("*"+name+"*");}

public String toString(){return
super.toString()+
          "t"+salary;}
public void inrcSalary(float x){salary += x;}

{
Inheritance
• Software reusability
• Create new class from existing class
   – Absorb existing class’s data and behaviors
   – Enhance with new capabilities

• A class that is derived from another class is called a subclass
  (also a derived, extended , or child class).
• The class from which the subclass is derived is called
  a superclass (also a base class or a parent class).
• Subclass extends superclass
       • Subclass
           – More specialized group of objects
           – Behaviors inherited from superclass
               » Can customize
• Each subclass can become the superclass for future subclasses.
Inheritance (cont.)
• Class hierarchy
  – Direct superclass
     • Inherited explicitly (one level up hierarchy)
  – Indirect superclass
     • Inherited two or more levels up hierarchy
  – Single inheritance
     • Inherits from one superclass
  – Multiple inheritance
     • Inherits from multiple superclasses
        – Java does not support multiple inheritance
Inheritance (cont.)
• “is-a” vs. “has-a”
  – “is-a”
     • Inheritance
     • subclass object treated as superclass object
     • Example: Car is a vehicle
        – Vehicle properties/behaviors also car properties/behaviors
  – “has-a”
     • Composition
     • Object contains one or more objects of other classes as
       members
     • Example: Car has wheels
Superclasses and Subclasses
– Superclass typically represents larger set of
  objects than subclasses
   • Example:
      – superclass: Vehicle
          » Cars, trucks, boats, bicycles, …
      – subclass: Car
          » Smaller, more-specific subset of vehicles
Inheritance Hierarchy
• Inheritance relationships: tree-like hierarchy structure

                                     CommunityMember




                              Employee      Student   Alumnus




                        Faculty          Staff




             Administrator    Teacher



      Inheritance hierarchy for university CommunityMembers
Inheritance Hierarchy


                               Shape




    TwoDimensionalShape                   ThreeDimensionalShape




Circle    Square    Triangle           Sphere      Cube   Tetrahedron




               Inheritance hierarchy for Shapes.
protected Members
• protected access
  – Intermediate level of protection between
    public and private
  – protected members accessible to
     • superclass members
     • subclass members
     • Class members in the same package
  – Subclass access superclass member
     • Keyword super and a dot (.)
Relationship between Superclasses and Subclasses

 • Using protected instance variables
   – Advantages
      • subclasses can modify values directly
      • Slight increase in performance
         – Avoid set/get function call overhead
   – Disadvantages
      • No validity checking
         – subclass can assign illegal value
      • Implementation dependent
         – subclass methods more likely dependent on superclass
           implementation
         – superclass implementation changes may result in subclass
           modifications
What You Can Do in a Subclass
• A subclass inherits all of the public and protected members of its
  parent, no matter what package the subclass is in.

• If the subclass is in the same package as its parent, it also inherits
  the package-access members of the parent.

• You can use the inherited members as is, replace them, hide them,
  or supplement them with new members.

• The inherited fields can be used directly, just like any other fields.

• You can declare a field in the subclass with the same name as the
  one in the superclass, thus hiding it (not recommended).

• You can declare new fields in the subclass that are not in the
  superclass.
What You Can Do in a Subclass (cont.)
• The inherited methods can be used directly as they are.

• You can write a new instance method in the subclass that has the
  same signature as the one in the superclass, thus overriding it.

• You can write a new static method in the subclass that has the
  same signature as the one in the superclass, thus hiding it.

• You can declare new methods in the subclass that are not in the
  superclass.

• You can write a subclass constructor that invokes the constructor of
  the superclass, either implicitly or by using the keyword super.
Example
Point/circle inheritance hierarchy
   • Point
       – x-y coordinate pair
       – Methods:
   • Circle
       – x-y coordinate pair
       – Radius
public class Point extends Object {
           protected int x, y; // coordinates of the Point
           public Point() // no-argument constructor
           {
Point         x = 0;
              y = 0;
Class      }
              System.out.println( "Point constructor: " + this );

           public Point( int xCoordinate, int yCoordinate ) // constructor
           {
              x = xCoordinate;
              y = yCoordinate;
              System.out.println( "Point constructor: " + this );
           }
           protected void finalize() // finalizer
           {
              System.out.println( "Point finalizer: " + this );
           }
           // convert Point into a String representation
           public String toString()
           {
              return "[" + x + ", " + y + "]";
           }
        } // end class Point
Circle Class
public class Circle extends Point {   // inherits from Point
   protected double radius;

  // no-argument constructor
  public Circle()
  {
     // implicit call to superclass constructor here
     radius = 0;
     System.out.println( "Circle constructor: " + this );
  }

  // Constructor
  public Circle( double circleRadius, int xCoordinate, int yCoordinate
  )
  {
     // call superclass constructor
     super( xCoordinate, yCoordinate );
     radius = circleRadius;
     System.out.println( "Circle constructor: " + this);
  }
Circle Class (cont.)
    protected void finalize() // finalizer
    {
       System.out.println( " Circle finalizer: " + this );
    }
    // convert the circle into a String representation
    public String toString()
    {
       return "Center = " + super.toString() +
              "; Radius = " + radius;

    }
}   // end class Circle
Point and Circle Test
public class Test {
   // test when constructors and finalizers are called
   public static void main( String args[] )
   { Point P = new Point();
      Circle circle1, circle2;
      circle1 = new Circle( 4.5, 72, 29 );
      circle2 = new Circle( 10, 5, 5 );
      P = null;        // mark for garbage collection
      circle1 = null; // mark for garbage collection
      circle2 = null; // mark for garbage collection
      System.gc();     // call the garbage collector
   }                   Point constructor: [0, 0]
                        Point constructor: Center = [72, 29]; Radius = 0.0
}   // end class Test   Circle constructor: Center = [72, 29]; Radius = 4.5
                        Point constructor: Center = [5, 5]; Radius = 0.0
                        Circle constructor: Center = [5, 5]; Radius = 10.0
                        Circle finalizer: Center = [5, 5]; Radius = 10.0
                        Point finalizer: Center = [5, 5]; Radius = 10.0
                        Circle finalizer: Center = [72, 29]; Radius = 4.5
                        Point finalizer: Center = [72, 29]; Radius = 4.5
                        Point finalizer: [0, 0]
Object Class
• All classes in Java inherit directly or indirectly from the Object
  class (package java.lang),
• So, its 11 methods are inherited by all other classes.
Method Summary
clone( )
  Creates and returns a copy of this object.
equals(Object obj)
       Indicates whether some other object is "equal to" this one.
finalize()
       Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
getClass()
       Returns the runtime class of this Object.
hashCode()
       Returns a hash code value for the object.
toString()
       Returns a string representation of the object.
Object Class (cont.)
notify()
      Wakes up a single thread that is waiting on this object's monitor.
notifyAll()
      Wakes up all threads that are waiting on this object's monitor.

wait()
      Causes the current thread to wait until another thread invokes the notify() method
or the notifyAll() method for this object.
wait(long timeout)
      Causes the current thread to wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
wait(long timeout, int nanos)
      Causes the current thread to wait until another thread invokes the notify() method
or the notifyAll() method for this object, or some other thread interrupts the current
thread, or a certain amount of real time has elapsed.
Object Cloning

public class Point implements Cloneable{
-----
-----
------
public Object clone() // raise visibility level to public
{
     try
    {     return super.clone();}
     catch (CloneNotSupportedException e) { return null; }
   }
}                                                   public class Test {
                                                      public static void main( String args[] )
--------                                               {
-------                                                 Point p1=new Point(10,30);
}                                                       Point p2= (Point) p1.clone();
                                                        p1.setx(500);
                                                        System.out.println(p1+"n"+p2);
                                                     }} // end class Test
equals method
                                               public class Point{
                                                 protected int x, y;
                                               public void setx(int x){this.x=x;}
public class Test {
                                               public void multiply(Point p){
    public static void main( String args[] )
                                                 this.x=p.x*p.x;
 { Point p1=new Point(10,30);
                                                 this.y=p.y*p.y;}
Point p2=new Point(10,30);
                                                 public static void multiply(Point p1, Point p2){
                                                 p1.x= p2.x *p2.x;
if(p1.equals(p2))
                                                 p1.y= p2.y *p2.y;}
 { System.out.println("they are equals");
                                                public static boolean equals(Point p1, Point p2){
}
                                               if(p1.x==p2.x && p1.y==p2.y)return true;
                                               return false;}
if(Point.equals(p1,p2))
                                               public boolean equals(Object y){
 { System.out.println("they are equals");
                                                 Point p=(Point)y;
}
                                                 if(this.x==p.x && this.y==p.y)return true;
                                                 return false;}
} // end class Test
                                               public String toString() {
                                               return "[" + x + ", " + y + "]"; }

                                               } // end class Point

Contenu connexe

Tendances

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
11slide
11slide11slide
11slideIIUM
 
Unit3 java
Unit3 javaUnit3 java
Unit3 javamrecedu
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Swift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionSwift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionKwang Woo NAM
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
 
Simple class and object examples in java
Simple class and object examples in javaSimple class and object examples in java
Simple class and object examples in javaHarish Gyanani
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Majid Saeed
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 

Tendances (20)

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
11slide
11slide11slide
11slide
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
04inherit
04inherit04inherit
04inherit
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Swift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionSwift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extension
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 
Core C#
Core C#Core C#
Core C#
 
Simple class and object examples in java
Simple class and object examples in javaSimple class and object examples in java
Simple class and object examples in java
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 

En vedette

Oop inheritance
Oop inheritanceOop inheritance
Oop inheritanceZubair CH
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator OverloadingHadziq Fabroyir
 
OOP Chapter 8 : Inheritance
OOP Chapter 8 : InheritanceOOP Chapter 8 : Inheritance
OOP Chapter 8 : InheritanceAtit Patumvan
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.MASQ Technologies
 
#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop InheritanceHadziq Fabroyir
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programmingAshita Agrawal
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 

En vedette (15)

Inheritance
InheritanceInheritance
Inheritance
 
Oop inheritance
Oop inheritanceOop inheritance
Oop inheritance
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
OOP Chapter 8 : Inheritance
OOP Chapter 8 : InheritanceOOP Chapter 8 : Inheritance
OOP Chapter 8 : Inheritance
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
 
#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance
 
Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming
 
OOP Inheritance
OOP InheritanceOOP Inheritance
OOP Inheritance
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
04 inheritance
04 inheritance04 inheritance
04 inheritance
 

Similaire à C h 04 oop_inheritance

Similaire à C h 04 oop_inheritance (20)

7 inheritance
7 inheritance7 inheritance
7 inheritance
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).ppt
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Core java oop
Core java oopCore java oop
Core java oop
 
Java Methods
Java MethodsJava Methods
Java Methods
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Java02
Java02Java02
Java02
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Java basic
Java basicJava basic
Java basic
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java session4
Java session4Java session4
Java session4
 

Dernier

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

C h 04 oop_inheritance

  • 1. Chapter 04: Object Oriented Programming - Inheritance -
  • 2. public class Employee { public class Part extends Employee { private String name; private float perHour; private float noOfHours; public Employee(String name){this.name=name;} public Part(String name, float perHour, float public Employee(){name="No Name";} noOfHours){ super(name); this.perHour=perHour; this.noOfHours=noOfHours;} public String toString(){return name;} } public Part(float perHour) {this.perHour=perHour;} public class Full extends Employee { public String toString(){return private float salary; super.toString()+"t"+perHour+"t"+noOfHours;} public void inrcnoOfHours(float x) public Full(String name, float salary){ {noOfHours += x;} super(name); public float paid(){return perHour * noOfHours;}} this.salary=salary;} public class Test { public static void main(String[] args) { public Full(float salary){this.salary=salary;} Full fe1= new Full("Ahmad", 1000f); Full fe2= new Full(2000f); public String toString(){return System.out.println(fe1+"n"+fe2); super.toString()+"t"+salary;} Part pe3=new Part("Rami",20f,50f); public void inrcSalary(float x){salary += x;} Part pe4=new Part(35f); } pe3.inrcnoOfHours(50); System.out.println(pe3+"n"+pe4);}}
  • 3. public class Employee{ private String name; public Employee(String name){this.name=name;} public Employee(){name="No Name";} public class Full extends Employee { private float salary; public void setName(String name){this.name=name;} public Full(String name, float salary){ super(name); public String toString(){return name;} this.salary=salary;} { public Full(float salary){this.salary=salary;} public void setName(String name){ super.setName("*"+name+"*");} public String toString(){return super.toString()+ "t"+salary;} public void inrcSalary(float x){salary += x;} {
  • 4. Inheritance • Software reusability • Create new class from existing class – Absorb existing class’s data and behaviors – Enhance with new capabilities • A class that is derived from another class is called a subclass (also a derived, extended , or child class). • The class from which the subclass is derived is called a superclass (also a base class or a parent class). • Subclass extends superclass • Subclass – More specialized group of objects – Behaviors inherited from superclass » Can customize • Each subclass can become the superclass for future subclasses.
  • 5. Inheritance (cont.) • Class hierarchy – Direct superclass • Inherited explicitly (one level up hierarchy) – Indirect superclass • Inherited two or more levels up hierarchy – Single inheritance • Inherits from one superclass – Multiple inheritance • Inherits from multiple superclasses – Java does not support multiple inheritance
  • 6. Inheritance (cont.) • “is-a” vs. “has-a” – “is-a” • Inheritance • subclass object treated as superclass object • Example: Car is a vehicle – Vehicle properties/behaviors also car properties/behaviors – “has-a” • Composition • Object contains one or more objects of other classes as members • Example: Car has wheels
  • 7. Superclasses and Subclasses – Superclass typically represents larger set of objects than subclasses • Example: – superclass: Vehicle » Cars, trucks, boats, bicycles, … – subclass: Car » Smaller, more-specific subset of vehicles
  • 8. Inheritance Hierarchy • Inheritance relationships: tree-like hierarchy structure CommunityMember Employee Student Alumnus Faculty Staff Administrator Teacher Inheritance hierarchy for university CommunityMembers
  • 9. Inheritance Hierarchy Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron Inheritance hierarchy for Shapes.
  • 10. protected Members • protected access – Intermediate level of protection between public and private – protected members accessible to • superclass members • subclass members • Class members in the same package – Subclass access superclass member • Keyword super and a dot (.)
  • 11. Relationship between Superclasses and Subclasses • Using protected instance variables – Advantages • subclasses can modify values directly • Slight increase in performance – Avoid set/get function call overhead – Disadvantages • No validity checking – subclass can assign illegal value • Implementation dependent – subclass methods more likely dependent on superclass implementation – superclass implementation changes may result in subclass modifications
  • 12. What You Can Do in a Subclass • A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. • If the subclass is in the same package as its parent, it also inherits the package-access members of the parent. • You can use the inherited members as is, replace them, hide them, or supplement them with new members. • The inherited fields can be used directly, just like any other fields. • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). • You can declare new fields in the subclass that are not in the superclass.
  • 13. What You Can Do in a Subclass (cont.) • The inherited methods can be used directly as they are. • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. • You can declare new methods in the subclass that are not in the superclass. • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
  • 14. Example Point/circle inheritance hierarchy • Point – x-y coordinate pair – Methods: • Circle – x-y coordinate pair – Radius
  • 15. public class Point extends Object { protected int x, y; // coordinates of the Point public Point() // no-argument constructor { Point x = 0; y = 0; Class } System.out.println( "Point constructor: " + this ); public Point( int xCoordinate, int yCoordinate ) // constructor { x = xCoordinate; y = yCoordinate; System.out.println( "Point constructor: " + this ); } protected void finalize() // finalizer { System.out.println( "Point finalizer: " + this ); } // convert Point into a String representation public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point
  • 16. Circle Class public class Circle extends Point { // inherits from Point protected double radius; // no-argument constructor public Circle() { // implicit call to superclass constructor here radius = 0; System.out.println( "Circle constructor: " + this ); } // Constructor public Circle( double circleRadius, int xCoordinate, int yCoordinate ) { // call superclass constructor super( xCoordinate, yCoordinate ); radius = circleRadius; System.out.println( "Circle constructor: " + this); }
  • 17. Circle Class (cont.) protected void finalize() // finalizer { System.out.println( " Circle finalizer: " + this ); } // convert the circle into a String representation public String toString() { return "Center = " + super.toString() + "; Radius = " + radius; } } // end class Circle
  • 18. Point and Circle Test public class Test { // test when constructors and finalizers are called public static void main( String args[] ) { Point P = new Point(); Circle circle1, circle2; circle1 = new Circle( 4.5, 72, 29 ); circle2 = new Circle( 10, 5, 5 ); P = null; // mark for garbage collection circle1 = null; // mark for garbage collection circle2 = null; // mark for garbage collection System.gc(); // call the garbage collector } Point constructor: [0, 0] Point constructor: Center = [72, 29]; Radius = 0.0 } // end class Test Circle constructor: Center = [72, 29]; Radius = 4.5 Point constructor: Center = [5, 5]; Radius = 0.0 Circle constructor: Center = [5, 5]; Radius = 10.0 Circle finalizer: Center = [5, 5]; Radius = 10.0 Point finalizer: Center = [5, 5]; Radius = 10.0 Circle finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: [0, 0]
  • 19. Object Class • All classes in Java inherit directly or indirectly from the Object class (package java.lang), • So, its 11 methods are inherited by all other classes. Method Summary clone( ) Creates and returns a copy of this object. equals(Object obj) Indicates whether some other object is "equal to" this one. finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. getClass() Returns the runtime class of this Object. hashCode() Returns a hash code value for the object. toString() Returns a string representation of the object.
  • 20. Object Class (cont.) notify() Wakes up a single thread that is waiting on this object's monitor. notifyAll() Wakes up all threads that are waiting on this object's monitor. wait() Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. wait(long timeout) Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. wait(long timeout, int nanos) Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
  • 21. Object Cloning public class Point implements Cloneable{ ----- ----- ------ public Object clone() // raise visibility level to public { try { return super.clone();} catch (CloneNotSupportedException e) { return null; } } } public class Test { public static void main( String args[] ) -------- { ------- Point p1=new Point(10,30); } Point p2= (Point) p1.clone(); p1.setx(500); System.out.println(p1+"n"+p2); }} // end class Test
  • 22. equals method public class Point{ protected int x, y; public void setx(int x){this.x=x;} public class Test { public void multiply(Point p){ public static void main( String args[] ) this.x=p.x*p.x; { Point p1=new Point(10,30); this.y=p.y*p.y;} Point p2=new Point(10,30); public static void multiply(Point p1, Point p2){ p1.x= p2.x *p2.x; if(p1.equals(p2)) p1.y= p2.y *p2.y;} { System.out.println("they are equals"); public static boolean equals(Point p1, Point p2){ } if(p1.x==p2.x && p1.y==p2.y)return true; return false;} if(Point.equals(p1,p2)) public boolean equals(Object y){ { System.out.println("they are equals"); Point p=(Point)y; } if(this.x==p.x && this.y==p.y)return true; return false;} } // end class Test public String toString() { return "[" + x + ", " + y + "]"; } } // end class Point