1 / 91

Bölüm 10 –Pol imorfizm

Bölüm 10 –Pol imorfizm. Outline 10.1 Polimorfizm 10.2 Miras Hiyerarşisinde Objeler arasındaki İlişki 10.2.1 Altsınıf objelerinin süper sınıf metotlarını çağırması 10.2.2 Süper sınıf referanlarna alt sınıf referans değeri atama

mateo
Download Presentation

Bölüm 10 –Pol imorfizm

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Bölüm 10 –Polimorfizm Outline 10.1 Polimorfizm 10.2 Miras Hiyerarşisinde Objeler arasındaki İlişki 10.2.1 Altsınıf objelerinin süper sınıf metotlarını çağırması 10.2.2 Süper sınıf referanlarna alt sınıf referans değeri atama 10.2.3 Süper sınıf referanslardan alt sınıf metotları çağırmak 10.3Soyut Sınıf ve Metodlar 10.4Arabirimler 10.5İçiçe Sınıflar

  2. Polimorfizm • Birçok altsınıf benzer olaylar için farklı metodları vardır. • Mesala bir hayvanat bahçesindeki hayvanların seslerinin simulasyonunu yapacaksınız. • Fakat her hayvanın ses çıkarması farklıdır. • Miras konusundaki örneğe yeniden bakalım !!

  3. class Animal { public void makeNoise ( ) { System.out.println (“I am an animal.”); } // of makeNoise } // of Animal classFish extendsAnimal { public void makeNoise( ) { System.out.println (“Glug glug gurgle gurgle”); } // of makeNoise } // of Fish classBirdextendsAnimal { public void makeNoise( ) { System.out.println(“Tweet tweet flap flap”); } // of makeNoise } // of Bird classDog extendsAnimal { public void makeNoise ( ) { System.out.println(“Sniff sniff woof woof”); } // of makeNoise public void bark ( ) { System.out.println(“Arf Arf”); } // of bark } // of Dog

  4. class Driver { public static void main (String[ ] argv) { Animal[ ] animalArray = new Animal[3]; int iIndex; animalArray[0] = new Bird( ); animalArray[1] = new Dog( ); animalArray[2] = new Fish( ); for (iIndex=0; iIndex < animalArray.length;iIndex++) { animalArray[iIndex].makeNoise( ); } // of for } // of main } // of Driver Output: Tweet tweet flap flap Sniff sniff woof woof Glug glug gurgle gurgle All animals can makeNoise, so any member of the array can makeNoise

  5. Polimorfizm • Miras,genel bir sınıfın ,tüm türevleri için ortak olan metotlar tanımlamasına ve altsınıfların bunların hepsi yada bir kısmına özel olarak gerçeklerştirilmesine izin verir. • Bu işe bindirilmiş metotlar (overriding) denir. • Bindirilmiş metotlar polimorfizmin “bir arabirim, birden çok metot” özelliğini gerçekleştirmenin bir başka yoludur. • Java bunu süper sınıf referansları ile yapar. • Hatırla!! – alt-sınıf is a süper-sınıf (Fish is a animal) • Tersi doğru değil

  6. Bellek Durumu Object Fish fTemp; fTemp = new Fish(0); toString() Animal int numLegs = 0 String strType toString(); move(); Fish move(); fTemp

  7. Wow. Object oTemp; oTemp = new Fish(0); Object toString() Animal int numLegs = 0 String strType toString(); move(); A single Fish instance Fish move(); oTemp

  8. Object toString() Animal int numLegs = 0 String strType toString(); move(); Fish move(); Ahh. So we can just make new reference types and have them point into our block at a different locations. By ‘twiddling’ the reference into our block of memory, we can polymorph the object. Animal aTemp; aTemp = new Fish(0); aTemp We adjust where reference points, so that it reflects its type.

  9. Hey, Cool Object toString() Animal int numLegs = 3 String strType toString(); move(); Fish Fish move(); ref That’s a simple example of polymorphism.

  10. Hey, Cool Object toString() Animal int numLegs = 3 String strType toString(); move(); Animal Fish move(); ref That’s a simple example of polymorphism.

  11. Hey, Cool It’s the same object in memory. We just change the reference type pointing to it. Object toString() Animal int numLegs = 3 String strType toString(); move(); Object Fish move(); ref That’s a simple example of polymorphism.

  12. Many forms One object Polymorphism Object toString() Animal int numLegs = 3 String strType toString(); move(); <type> Fish move(); ref Literally, polymorphism means “Many forms” So for us we take it to imply, "One object; many forms”

  13. Object Object Object toString() toString() toString() Animal Animal Animal int numLegs = 3 String strType toString(); move(); int numLegs = 0 String strType toString(); move(); int numLegs = 2 String strType toString(); move(); Dog Fish Bird move(); bark(); move(); move(); Thus So we have three box groupings that represent arbitrary instances of Fish, Dog and Bird, pointed to by any appropriate reference type. fTemp dTemp bTemp Fish fTemp = new Fish(0); Dog dTemp = new Dog(3); Bird bTemp = new Bird(2);

  14. Polymorphism class Driver2 { public static void main(String[ ] argv) { Animal[ ] = animalArray[3]; Dog d; int iIndex; animalArray[0] = new Bird( ); animalArray[1] = new Dog( ); animalArray[2] = new Fish( ); for (1=0; 1 < animalArray.length; iIndex++) if (animalArray[iIndex] instanceof Dog) { d = (Dog) animalArray[iIndex]; d.bark( ); } // if } // main } // Driver2 We cast before calling bark() because only dogs can bark. So some array members cannot execute the method

  15. Polymorphism • Casting: • used here to give an object of a superclass the form of the appropriate subclass, e.g., • if (animalArray[iIndex] instanceof Dog) • { • animalArray[iIndex].bark(); • } • would produce an error because objects of class Animal have no method called bark. So, we first cast what instanceof tells us is a Dog asaDog. • if (animalArray[iIndex] instanceof Dog) • { • d = (Dog) animalArray[iIndex] • d.bark( ); • }

  16. Casting … Why? Keyword instanceof: Used to interrogate an object to see if it is an instance of the specified class, e.g. “Is this particular animal of class Dog?” • Question: • If Java can determine that a given Animal is or is nota Dog (via instanceof), then: • Why the need to cast it to a Dog object before Java can recognize that it can bark? • Why can’t Java do it for us?

  17. Casting… Why? Answer: difference between compile-time and run-time type checking. Sourcecode Compile Bytecode JVMInterpreter Programruns errors errors • Run-time Errors: • Those that are discernable only when the program is running with actual data values. • Question of execution legality: • “Is it legal for this variable to have the actual value assigned to it?”, e.g., • animalArray[<badIndex>] = someAnimal • Statement is legal, but particular index value isn’t. • Compile-time Errors: • Those that are discernable • (seçmek,ayırt etmek) • without the program executing. • Question of language legality: “Is this a legal statement?” e.g., • iIndex = strName;Statement is not legal.

  18. Casting… Why? if (animalArray[iIndex] instanceof Dog){ animalArray[iIndex].bark(); } if (animalArray[iIndex] instanceof Dog) { d = (Dog) animalArray[iIndex]; d.bark( ); } • 1st line is legal. • 2nd line isn’t (unless array has Dog). • We can see that 1st line guarantees 2nd is legal. • Compiler cannot see inter-statement dependencies… unless compiler runs whole program with all possible data sets! • Runtime system could tell easily. . . BUT. . . We want most checking at compile-time for reasons of bothperformance and correctness. • Here, legality of each line of code can be evaluated at compile time. • Legality of each line discernable without worrying about inter-statement dependencies, i.e., each line can stand by itself. • Can be sure that code is legal (not sometimes-legal).A Good Use for Casting: • Resolving polymorphic ambiguities for the compiler.

  19. 10.2 Miras Hiyerarşisi içinde Objeler arasında İlişki • Önceki bölümde (Bölüm 9.4), • Circlesınfı Point sınfından miras almıştı. • PointveCirclenesnelerinin referanslarını kullanarak metodlarını çağırıyorduk. • İpucu • Altsınıf nesnesi süper sınıf nesnesi gibi davranabilir. • “is-a” ilişkisi (Çember noktalardan oluşur.) • Süpersınıf nesnesi altsınıf nesnesi değildir.

  20. 10.2.1 Altsınıf nesnelerinden süper sınıf referansı ile alt sınıf metodlarını çağırmak • Süper sınıf ve altsınıf nesnelerinde referanslar saklamak • Süpersınıf referansını süpersınıf türünden tanıtılmış değişkene atamak • Supers_değişkensupers_referans • Altsınıf referansını altsınıf türünden tanıtılmış değişkene atamak • Alts_değişkenalts_referans • Altsınıf referansını süpersınıf değişkenine atamak • Supers_değişkenalts_referans • “is a” ilişkisi

  21. Assign superclass reference to superclass-type variable Assign subclass reference to subclass-type variable Invoke toString on superclass object using superclass variable Invoke toString on subclass object using subclass variable 1 // Fig. 10.1: HierarchyRelationshipTest1.java 2 // Assigning superclass and subclass references to superclass- and 3 // subclass-type variables. 4 import javax.swing.JOptionPane; 5 6 publicclass HierarchyRelationshipTest1 { 7 8 publicstaticvoid main( String[] args ) 9 { 10 // assign superclass reference to superclass-type variable 11 Point3 point = new Point3( 30, 50 ); 12 13 // assign subclass reference to subclass-type variable 14 Circle4 circle = new Circle4( 120, 89, 2.7 ); 15 16 // invoke toString on superclass object using superclass variable 17 String output = "Call Point3's toString with superclass" + 18 " reference to superclass object: \n" + point.toString(); 19 20 // invoke toString on subclass object using subclass variable 21 output += "\n\nCall Circle4's toString with subclass" + 22 " reference to subclass object: \n" + circle.toString(); 23 HierarchyRelationshipTest1.javaLine 11Assign superclass reference to superclass-type variableLine 14 Assign subclass reference to subclass-type variableLine 17Invoke toString on superclass object using superclass variableLine 22Invoke toString on subclass object using subclass variable

  22. Assign subclass reference to superclass-type variable Invoke toString on subclass object using superclass variable 24 // invoke toString on subclass object using superclass variable 25 Point3 pointRef = circle; 26 output += "\n\nCall Circle4's toString with superclass" + 27 " reference to subclass object: \n" + pointRef.toString(); 28 29 JOptionPane.showMessageDialog( null, output ); // display output 30 31 System.exit( 0 ); 32 33 } // end main 34 35 } // end class HierarchyRelationshipTest1 HierarchyRelationshipTest1.javaLine 25Assign subclass reference to superclass-type variable.Line 27Invoke toString on subclass object using superclass variable.

  23. 10.2.2 Altsınıf değişken tipleri ile süper sınıf referanslarını kullanmak • Öncekiörnek • Altsınıf referansını süpersınıf değişkenine atamak • Circle “is a” Point • Süpersınıf referanslarını altsınıf tipli değişkenlere atamak • Derleme hatası • “is a” türünde ilişki yok • Point is not a Circle • Circlesınıfının sahip olup Point sınıfının sahip olmadığı data/metodlar var. • setRadius (Circleda tanımlı) Pointsınıfında tanımlı değil. • Süpersınıf referansını altsınıf referansına dönüştürmek. • downcasting olarak adlandırılır. • Altsınıf işlevlerini çağırma

  24. Assigning superclass reference to subclass-type variable causes compiler error 1 // Fig. 10.2: HierarchyRelationshipTest2.java 2 // Attempt to assign a superclass reference to a subclass-type variable. 3 4 publicclass HierarchyRelationshipTest2 { 5 6 publicstaticvoid main( String[] args ) 7 { 8 Point3 point = new Point3( 30, 50 ); 9 Circle4 circle; // subclass-type variable 10 11 // assign superclass reference to subclass-type variable 12 circle = point;// Error: a Point3 is not a Circle4 13 } 14 15 } // end class HierarchyRelationshipTest2 HierarchyRelationshipTest2.javaLine 12Assigning superclass reference to subclass-type variable causes compiler error. HierarchyRelationshipTest2.java:12: incompatible types found : Point3 required: Circle4 circle = point; // Error: a Point3 is not a Circle4 ^ 1 error

  25. 10.2.3 Süper sınıf değişken tipine göre altsınıf metodları çağırmak • Süpersınıf referansı ile altsınıf metodu çağırmak • Derleme hatası • Altsınıf metodları süpersınıf metodları değiller.

  26. 1 // Fig. 10.3: HierarchyRelationshipTest3.java 2 // Attempting to invoke subclass-only member methods through 3 // a superclass reference. 4 5 publicclass HierarchyRelationshipTest3 { 6 7 publicstaticvoid main( String[] args ) 8 { 9 Point3 point; 10 Circle4 circle = new Circle4( 120, 89, 2.7 ); 11 12 point = circle; // aim superclass reference at subclass object 13 14 // invoke superclass (Point3) methods on subclass 15 // (Circle4) object through superclass reference 16 int x = point.getX(); 17 int y = point.getY(); 18 point.setX( 10 ); 19 point.setY( 20 ); 20 point.toString(); 21 HierarchyRelationshipTest3.java

  27. Attempt to invoke subclass-only (Circle4) methods on subclass object through superclass (Point3) reference. 22 // attempt to invoke subclass-only (Circle4) methods on 23 // subclass object through superclass (Point3) reference 24 double radius = point.getRadius(); 25 point.setRadius( 33.33 ); 26 double diameter = point.getDiameter(); 27 double circumference = point.getCircumference(); 28 double area = point.getArea(); 29 30 } // end main 31 32 } // end class HierarchyRelationshipTest3 HierarchyRelationshipTest3.javaLines 24-28Attempt to invoke subclass-only (Circle4) methods on subclass object through superclass (Point3) reference.

  28. HierarchyRelationshipTest3.java:24: cannot resolve symbol symbol : method getRadius () location: class Point3 double radius = point.getRadius(); ^ HierarchyRelationshipTest3.java:25: cannot resolve symbol symbol : method setRadius (double) location: class Point3 point.setRadius( 33.33 ); ^ HierarchyRelationshipTest3.java:26: cannot resolve symbol symbol : method getDiameter () location: class Point3 double diameter = point.getDiameter(); ^ HierarchyRelationshipTest3.java:27: cannot resolve symbol symbol : method getCircumference () location: class Point3 double circumference = point.getCircumference(); ^ HierarchyRelationshipTest3.java:28: cannot resolve symbol symbol : method getArea () location: class Point3 double area = point.getArea(); ^ 5 errors HierarchyRelationshipTest3.java

  29. 10.4 Soyut (Abstract)Sınıflar ve Metodlar • Soyut (abstract)sınıflar • Süpersınıflar soyut sınıflar olarak adlandırabilir miyiz? • Nesne oluşturamazlar. • Tam bir sınıf değildirler. • Altsınıflar soyut sınıfının boş kısımlarını doldururlar. • Somut (concrete)sınıflar • Nesne oluşturabilirler. • Bütün metodlar tanımlıdır. • Detaylar vardır.

  30. 10.4 Soyut (Abstract)Sınıflar ve Metodlar (devam) • Soyut sınıf yapmak için • Sınıf abstract anahtar sözü ile tanımlanır. • Bir yada daha fazla soyut metod içerebilir. public abstract void draw(); • Soyut metodlar • İçinde herhengi bir kod bulundurmazlar, miras alınan sınıf tarafından içleri doldurulur.

  31. 10.4 Soyut (Abstract)Sınıflar ve Metodlar (devam) • Örnek uygulama • Soyut sınıf:Shape • drawmetodunu soyut olarak tanımlıyor. • Circle, Triangle, Rectanglesınıfları Shape sınıfını miras alıyorlar. • Her bir sınıf draw metodunu tanımlamalı.

  32. 10.5 Örnek Uygulama: Soyut Sınıfı Miras Alma • Soyut süper sınıf :Shape • Soyut metodlar • getName, print • İptal edilebilir (overridden) metodlar • getArea, getVolume • Varsayılan uygulama 0.0 dönderir. • Eğer iptal edilmezlerse süper sınıfın metodunu kullanırlar. • Altsınıflar:Point, Circle, Cylinder

  33. Cylinder Circle Point Shape 10.5 Örnek Uygulama: Soyut Sınıfı Miras Alma Fig. 10.4 Shape hierarchy class diagram.

  34. getArea getVolume getName print 0.0 pr2 0.0 0.0 = 0 = 0 "Circle" pr2h 0.0 0.0 [x,y] 2pr2 +2prh center=[x,y]; radius=r; height=h "Point" "Cylinder" Shape Point center=[x,y]; radius=r Circle Cylinder 10.6 Örnek Uygulama: Soyut Sınıfı Miras Alma Fig. 10.5 Polimorphic interface for the Shape hierarchy classes.

  35. Keyword abstract declares class Shape as abstract class Keyword abstract declares method getName as abstract method 1 // Fig. 10.6: Shape.java 2 // Shape abstract-superclass declaration. 3 4 publicabstractclass Shape extends Object { 5 6 // return area of shape; 0.0 by default 7 publicdouble getArea() 8 { 9 return0.0; 10 } 11 12 // return volume of shape; 0.0 by default 13 publicdouble getVolume() 14 { 15 return0.0; 16 } 17 18 // abstract method, overridden by subclasses 19 publicabstract String getName(); 20 21 } // end abstract class Shape Shape.javaLine 4Keyword abstract declares class Shape as abstract classLine 19Keyword abstract declares method getName as abstract method

  36. 1 // Fig. 10.7: Point.java 2 // Point class declaration inherits from Shape. 3 4 publicclass Point extends Shape { 5 privateint x; // x part of coordinate pair 6 privateint y; // y part of coordinate pair 7 8 // no-argument constructor; x and y default to 0 9 public Point() 10 { 11 // implicit call to Object constructor occurs here 12 } 13 14 // constructor 15 public Point( int xValue, int yValue ) 16 { 17 // implicit call to Object constructor occurs here 18 x = xValue; // no need for validation 19 y = yValue; // no need for validation 20 } 21 22 // set x in coordinate pair 23 publicvoid setX( int xValue ) 24 { 25 x = xValue; // no need for validation 26 } 27 Point.java

  37. Override abstract method getName. 28 // return x from coordinate pair 29 publicint getX() 30 { 31 return x; 32 } 33 34 // set y in coordinate pair 35 publicvoid setY( int yValue ) 36 { 37 y = yValue; // no need for validation 38 } 39 40 // return y from coordinate pair 41 publicint getY() 42 { 43 return y; 44 } 45 46 // override abstract method getName to return "Point" 47 public String getName() 48 { 49 return"Point"; 50 } 51 52 // override toString to return String representation of Point 53 public String toString() 54 { 55 return"[" + getX() + ", " + getY() + "]"; 56 } 57 58 } // end class Point Point.javaLines 47-50Override abstract method getName.

  38. 1 // Fig. 10.8: Circle.java 2 // Circle class inherits from Point. 3 4 publicclass Circle extends Point { 5 privatedouble radius; // Circle's radius 6 7 // no-argument constructor; radius defaults to 0.0 8 public Circle() 9 { 10 // implicit call to Point constructor occurs here 11 } 12 13 // constructor 14 public Circle( int x, int y, double radiusValue ) 15 { 16 super( x, y ); // call Point constructor 17 setRadius( radiusValue ); 18 } 19 20 // set radius 21 publicvoid setRadius( double radiusValue ) 22 { 23 radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); 24 } 25 Circle.java

  39. Override method getArea to return circle area 26 // return radius 27 publicdouble getRadius() 28 { 29 return radius; 30 } 31 32 // calculate and return diameter 33 publicdouble getDiameter() 34 { 35 return2 * getRadius(); 36 } 37 38 // calculate and return circumference 39 publicdouble getCircumference() 40 { 41 return Math.PI * getDiameter(); 42 } 43 44 // override method getArea to return Circle area 45 publicdouble getArea() 46 { 47 return Math.PI * getRadius() * getRadius(); 48 } 49 Circle.javaLines 45-48Override method getAreato return circle area.

  40. Override abstract method getName 50 // override abstract method getName to return "Circle" 51 public String getName() 52 { 53 return"Circle"; 54 } 55 56 // override toString to return String representation of Circle 57 public String toString() 58 { 59 return"Center = " + super.toString() + "; Radius = " + getRadius(); 60 } 61 62 } // end class Circle Circle.javaLines 51-54Override abstractmethod getName.

  41. 1 // Fig. 10.9: Cylinder.java 2 // Cylinder class inherits from Circle. 3 4 publicclass Cylinder extends Circle { 5 privatedouble height; // Cylinder's height 6 7 // no-argument constructor; height defaults to 0.0 8 public Cylinder() 9 { 10 // implicit call to Circle constructor occurs here 11 } 12 13 // constructor 14 public Cylinder( int x, int y, double radius, double heightValue ) 15 { 16 super( x, y, radius ); // call Circle constructor 17 setHeight( heightValue ); 18 } 19 20 // set Cylinder's height 21 publicvoid setHeight( double heightValue ) 22 { 23 height = ( heightValue < 0.0 ? 0.0 : heightValue ); 24 } 25 Cylinder.java

  42. Override abstract method getName Override method getArea to return cylinder area Override method getVolume to return cylinder volume 26 // get Cylinder's height 27 publicdouble getHeight() 28 { 29 return height; 30 } 31 32 // override abstract method getArea to return Cylinder area 33 publicdouble getArea() 34 { 35 return2 * super.getArea() + getCircumference() * getHeight(); 36 } 37 38 // override abstract method getVolume to return Cylinder volume 39 publicdouble getVolume() 40 { 41 returnsuper.getArea() * getHeight(); 42 } 43 44 // override abstract method getName to return "Cylinder" 45 public String getName() 46 { 47 return"Cylinder"; 48 } Cylinder.javaLines 33-36Override method getArea to return cylinder areaLines 39-42Override method getVolume to return cylinder volumeLines 45-48Override abstract method getName

  43. 49 50 // override toString to return String representation of Cylinder 51 public String toString() 52 { 53 returnsuper.toString() + "; Height = " + getHeight(); 54 } 55 56 } // end class Cylinder Cylinder.java

  44. 1 // Fig. 10.10: AbstractInheritanceTest.java 2 // Driver for shape, point, circle, cylinder hierarchy. 3 import java.text.DecimalFormat; 4 import javax.swing.JOptionPane; 5 6 publicclass AbstractInheritanceTest { 7 8 publicstaticvoid main( String args[] ) 9 { 10 // set floating-point number format 11 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 12 13 // create Point, Circle and Cylinder objects 14 Point point = new Point( 7, 11 ); 15 Circle circle = new Circle( 22, 8, 3.5 ); 16 Cylinder cylinder = new Cylinder( 20, 30, 3.3, 10.75 ); 17 18 // obtain name and string representation of each object 19 String output = point.getName() + ": " + point + "\n" + 20 circle.getName() + ": " + circle + "\n" + 21 cylinder.getName() + ": " + cylinder + "\n"; 22 23 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array 24 AbstractInheritanceTest.java

  45. Create an array of generic Shape objects Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array 25 // aim arrayOfShapes[ 0 ] at subclass Point object 26 arrayOfShapes[ 0 ] = point; 27 28 // aim arrayOfShapes[ 1 ] at subclass Circle object 29 arrayOfShapes[ 1 ] = circle; 30 31 // aim arrayOfShapes[ 2 ] at subclass Cylinder object 32 arrayOfShapes[ 2 ] = cylinder; 33 34 // loop through arrayOfShapes to get name, string 35 // representation, area and volume of every Shape in array 36 for ( int i = 0; i < arrayOfShapes.length; i++ ) { 37 output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + 38 arrayOfShapes[ i ].toString() + "\nArea = " + 39 twoDigits.format( arrayOfShapes[ i ].getArea() ) + 40 "\nVolume = " + 41 twoDigits.format( arrayOfShapes[ i ].getVolume() ); 42 } 43 44 JOptionPane.showMessageDialog( null, output ); // display output 45 46 System.exit( 0 ); 47 48 } // end main 49 50 } // end class AbstractInheritanceTest AbstractInheritanceTest.javaLines 26-32Create an array of generic Shape objectsLines 36-42Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array

  46. 10.7 Örnek Uygulama: Polimorfizim kullanarak Bordro Sistemi • Bordro programı oluşturalım • Soyut metodlar ve polimorfizm kullanalım • Problemimiz: • 4 tip çalışanımız var, ücretleri haftalık ödeniyor. • Salaried : sabit maaşlı • Hourly: saatlik maaş ödeniyor.(eğer 40 saati aşmış ise aşan saat kadar 1.5 katı ödeme yapılacak) • Commission: satış yüzdesi kadar maaş ödeniyor. • Base-plus-commission: sabit maaş + satışın belli miktarda yüzdesi)

  47. Employee SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee 10.9 Case Study: Payroll System Using Polymorphism • Süpersınıf:Employee • Soyut metod: earnings (kazanılanı geri dönderir) • Soyut olması lazım;çünki çalışan tipini bilmiyoruz. • Diğer sınıflar Employeesınıfından miras alıyor.

  48. Declares class Employee as abstract class. 1 // Fig. 10.12: Employee.java 2 // Employee abstract superclass. 3 4 publicabstractclass Employee { 5 private String firstName; 6 private String lastName; 7 private String socialSecurityNumber; 8 9 // constructor 10 public Employee( String first, String last, String ssn ) 11 { 12 firstName = first; 13 lastName = last; 14 socialSecurityNumber = ssn; 15 } 16 17 // set first name 18 publicvoid setFirstName( String first ) 19 { 20 firstName = first; 21 } 22 Employee.javaLine 4Declares class Employee as abstract class.

  49. 23 // return first name 24 public String getFirstName() 25 { 26 return firstName; 27 } 28 29 // set last name 30 publicvoid setLastName( String last ) 31 { 32 lastName = last; 33 } 34 35 // return last name 36 public String getLastName() 37 { 38 return lastName; 39 } 40 41 // set social security number 42 publicvoid setSocialSecurityNumber( String number ) 43 { 44 socialSecurityNumber = number; // should validate 45 } 46 Employee.java

More Related