SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie C h 04 oop_inheritance

Ähnlich wie 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
 

Kürzlich hochgeladen

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Kürzlich hochgeladen (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 

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