Sunum yükleniyor. Lütfen bekleyiniz

Sunum yükleniyor. Lütfen bekleyiniz

Bölüm 10 –Polimorfizm Outline 10.1 Polimorfizm

Benzer bir sunumlar


... konulu sunumlar: "Bölüm 10 –Polimorfizm Outline 10.1 Polimorfizm"— Sunum transkripti:

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

2 Birçok altsınıf benzer olaylar için farklı metodları vardır.
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 public void makeNoise ( ) { System.out.println (“I am an animal.”);
class Animal { public void makeNoise ( ) { System.out.println (“I am an animal.”); } // of makeNoise } // of Animal class Fish extends Animal { public void makeNoise( ) { (“Glug glug gurgle gurgle”); } // of Fish class Bird extends Animal { public void makeNoise( ) { System.out.println(“Tweet tweet flap flap”); } // of Bird class Dog extends Animal { public void makeNoise ( ) System.out.println(“Sniff sniff woof woof”); 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 Fish fTemp; fTemp = new Fish(0); fTemp Object Animal
toString() Animal int numLegs = 0 String strType toString(); move(); Fish move(); fTemp

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

8 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 int numLegs = 0 String strType toString(); move(); Object toString() Fish Animal aTemp; aTemp = new Fish(0); aTemp We adjust where reference points, so that it reflects its type.

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

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

11 Hey, Cool That’s a simple example of polymorphism.
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 Polymorphism Literally, polymorphism means “Many forms” So for
Object One 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 Thus So we have three box groupings that represent arbitrary instances of Fish, Dog and Bird, pointed to by any appropriate reference type. Object toString() Object toString() Animal int numLegs = 0 String strType toString(); move(); Object toString() Fish Animal int numLegs = 3 String strType toString(); move(); Animal int numLegs = 2 String strType toString(); move(); Dog move(); bark(); Bird move(); 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 as a 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 not a 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. Source code Compile Byte code JVM Interpreter Program runs 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] 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 both performance 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), Circle sınfı Point sınfından miras almıştı. Point ve Circle nesnelerinin 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 Süper sınıf ve altsınıf nesnelerinde referanslar saklamak
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
// Fig. 10.1: HierarchyRelationshipTest1.java // Assigning superclass and subclass references to superclass- and // subclass-type variables. import javax.swing.JOptionPane; 5 public class HierarchyRelationshipTest1 { 7 public static void main( String[] args ) { // assign superclass reference to superclass-type variable Point3 point = new Point3( 30, 50 ); 12 // assign subclass reference to subclass-type variable Circle4 circle = new Circle4( 120, 89, 2.7 ); 15 // invoke toString on superclass object using superclass variable String output = "Call Point3's toString with superclass" + " reference to superclass object: \n" + point.toString(); 19 // invoke toString on subclass object using subclass variable output += "\n\nCall Circle4's toString with subclass" + " reference to subclass object: \n" + circle.toString(); 23 HierarchyRelationshipTest1.java Line 11 Assign superclass reference to superclass-type variable Line 14 Assign subclass reference to subclass-type variable Line 17 Invoke toString on superclass object using superclass variable Line 22 Invoke toString on subclass object using subclass variable 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

22 Assign subclass reference to superclass-type variable
// invoke toString on subclass object using superclass variable Point3 pointRef = circle; output += "\n\nCall Circle4's toString with superclass" + " reference to subclass object: \n" + pointRef.toString(); 28 JOptionPane.showMessageDialog( null, output ); // display output 30 System.exit( 0 ); 32 } // end main 34 35 } // end class HierarchyRelationshipTest1 Assign subclass reference to superclass-type variable Invoke toString on subclass object using superclass variable HierarchyRelationshipTest1.java Line 25 Assign subclass reference to superclass-type variable. Line 27 Invoke 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 Circle sınıfının sahip olup Point sınıfının sahip olmadığı data/metodlar var. setRadius (Circle da tanımlı) Point sı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 1 // Fig. 10.2: HierarchyRelationshipTest2.java
// Attempt to assign a superclass reference to a subclass-type variable. 3 public class HierarchyRelationshipTest2 { 5 public static void main( String[] args ) { Point3 point = new Point3( 30, 50 ); Circle4 circle; // subclass-type variable 10 // assign superclass reference to subclass-type variable circle = point; // Error: a Point3 is not a Circle4 } 14 15 } // end class HierarchyRelationshipTest2 HierarchyRelationshipTest2.java Line 12 Assigning superclass reference to subclass-type variable causes compiler error. Assigning 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
// Attempting to invoke subclass-only member methods through // a superclass reference. 4 public class HierarchyRelationshipTest3 { 6 public static void main( String[] args ) { Point3 point; Circle4 circle = new Circle4( 120, 89, 2.7 ); 11 point = circle; // aim superclass reference at subclass object 13 // invoke superclass (Point3) methods on subclass // (Circle4) object through superclass reference int x = point.getX(); int y = point.getY(); point.setX( 10 ); point.setY( 20 ); point.toString(); 21 HierarchyRelationshipTest3.java

27 22 // attempt to invoke subclass-only (Circle4) methods on
// subclass object through superclass (Point3) reference double radius = point.getRadius(); point.setRadius( ); double diameter = point.getDiameter(); double circumference = point.getCircumference(); double area = point.getArea(); 29 } // end main 31 32 } // end class HierarchyRelationshipTest3 HierarchyRelationshipTest3.java Lines Attempt to invoke subclass-only (Circle4) methods on subclass object through superclass (Point3) reference. Attempt 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) point.setRadius( ); HierarchyRelationshipTest3.java:26: cannot resolve symbol symbol : method getDiameter () double diameter = point.getDiameter(); HierarchyRelationshipTest3.java:27: cannot resolve symbol symbol : method getCircumference () double circumference = point.getCircumference(); HierarchyRelationshipTest3.java:28: cannot resolve symbol symbol : method getArea () double area = point.getArea(); 5 errors HierarchyRelationshipTest3.java

29 10.4 Soyut (Abstract) Sınıflar ve Metodlar
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 draw metodunu soyut olarak tanımlıyor. Circle, Triangle, Rectangle sı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 10.5 Örnek Uygulama: Soyut Sınıfı Miras Alma
Circle Cylinder Point Shape Fig Shape hierarchy class diagram.

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

35 Keyword abstract declares class Shape as abstract class
// Fig. 10.6: Shape.java // Shape abstract-superclass declaration. 3 public abstract class Shape extends Object { 5 // return area of shape; 0.0 by default public double getArea() { return 0.0; } 11 // return volume of shape; 0.0 by default public double getVolume() { return 0.0; } 17 // abstract method, overridden by subclasses public abstract String getName(); 20 21 } // end abstract class Shape Shape.java Line 4 Keyword abstract declares class Shape as abstract class Line 19 Keyword abstract declares method getName as abstract method Keyword abstract declares class Shape as abstract class Keyword abstract declares method getName as abstract method

36 Point.java 1 // Fig. 10.7: Point.java
// Point class declaration inherits from Shape. 3 public class Point extends Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair 7 // no-argument constructor; x and y default to 0 public Point() { // implicit call to Object constructor occurs here } 13 // constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } 21 // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation } 27 Point.java

37 Point.java Lines 47-50 Override abstract method getName.
// return x from coordinate pair public int getX() { return x; } 33 // set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation } 39 // return y from coordinate pair public int getY() { return y; } 45 // override abstract method getName to return "Point" public String getName() { return "Point"; } 51 // override toString to return String representation of Point public String toString() { return "[" + getX() + ", " + getY() + "]"; } 57 58 } // end class Point Point.java Lines Override abstract method getName. Override abstract method getName.

38 Circle.java 1 // Fig. 10.8: Circle.java
// Circle class inherits from Point. 3 public class Circle extends Point { private double radius; // Circle's radius 6 // no-argument constructor; radius defaults to 0.0 public Circle() { // implicit call to Point constructor occurs here } 12 // constructor public Circle( int x, int y, double radiusValue ) { super( x, y ); // call Point constructor setRadius( radiusValue ); } 19 // set radius public void setRadius( double radiusValue ) { radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); } 25 Circle.java

39 Circle.java Lines 45-48 Override method getArea to return circle area.
// return radius public double getRadius() { return radius; } 31 // calculate and return diameter public double getDiameter() { return 2 * getRadius(); } 37 // calculate and return circumference public double getCircumference() { return Math.PI * getDiameter(); } 43 // override method getArea to return Circle area public double getArea() { return Math.PI * getRadius() * getRadius(); } 49 Circle.java Lines Override method getArea to return circle area. Override method getArea to return circle area

40 Circle.java Lines 51-54 Override abstract method getName.
// override abstract method getName to return "Circle" public String getName() { return "Circle"; } 55 // override toString to return String representation of Circle public String toString() { return "Center = " + super.toString() + "; Radius = " + getRadius(); } 61 62 } // end class Circle Override abstract method getName Circle.java Lines Override abstract method getName.

41 Cylinder.java 1 // Fig. 10.9: Cylinder.java
// Cylinder class inherits from Circle. 3 public class Cylinder extends Circle { private double height; // Cylinder's height 6 // no-argument constructor; height defaults to 0.0 public Cylinder() { // implicit call to Circle constructor occurs here } 12 // constructor public Cylinder( int x, int y, double radius, double heightValue ) { super( x, y, radius ); // call Circle constructor setHeight( heightValue ); } 19 // set Cylinder's height public void setHeight( double heightValue ) { height = ( heightValue < 0.0 ? 0.0 : heightValue ); } 25 Cylinder.java

42 Override method getArea to return cylinder area
// get Cylinder's height public double getHeight() { return height; } 31 // override abstract method getArea to return Cylinder area public double getArea() { return 2 * super.getArea() + getCircumference() * getHeight(); } 37 // override abstract method getVolume to return Cylinder volume public double getVolume() { return super.getArea() * getHeight(); } 43 // override abstract method getName to return "Cylinder" public String getName() { return "Cylinder"; } Override method getArea to return cylinder area Cylinder.java Lines Override method getArea to return cylinder area Lines Override method getVolume to return cylinder volume Lines Override abstract method getName Override method getVolume to return cylinder volume Override abstract method getName

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

44 1 // Fig. 10.10: AbstractInheritanceTest.java
// Driver for shape, point, circle, cylinder hierarchy. import java.text.DecimalFormat; import javax.swing.JOptionPane; 5 public class AbstractInheritanceTest { 7 public static void main( String args[] ) { // set floating-point number format DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 12 // create Point, Circle and Cylinder objects Point point = new Point( 7, 11 ); Circle circle = new Circle( 22, 8, 3.5 ); Cylinder cylinder = new Cylinder( 20, 30, 3.3, ); 17 // obtain name and string representation of each object String output = point.getName() + ": " + point + "\n" + circle.getName() + ": " + circle + "\n" + cylinder.getName() + ": " + cylinder + "\n"; 22 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array 24 AbstractInheritanceTest.java

45 Create an array of generic Shape objects
// aim arrayOfShapes[ 0 ] at subclass Point object arrayOfShapes[ 0 ] = point; 27 // aim arrayOfShapes[ 1 ] at subclass Circle object arrayOfShapes[ 1 ] = circle; 30 // aim arrayOfShapes[ 2 ] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder; 33 // loop through arrayOfShapes to get name, string // representation, area and volume of every Shape in array for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + arrayOfShapes[ i ].toString() + "\nArea = " + twoDigits.format( arrayOfShapes[ i ].getArea() ) + "\nVolume = " + twoDigits.format( arrayOfShapes[ i ].getVolume() ); } 43 JOptionPane.showMessageDialog( null, output ); // display output 45 System.exit( 0 ); 47 } // end main 49 50 } // end class AbstractInheritanceTest Create an array of generic Shape objects AbstractInheritanceTest.java Lines Create an array of generic Shape objects Lines Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array

46

47 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)

48 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 Employee sınıfından miras alıyor. Employee SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee

49 Employee.java Line 4 Declares class Employee as abstract class.
// Fig : Employee.java // Employee abstract superclass. 3 public abstract class Employee { private String firstName; private String lastName; private String socialSecurityNumber; 8 // constructor public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } 16 // set first name public void setFirstName( String first ) { firstName = first; } 22 Declares class Employee as abstract class. Employee.java Line 4 Declares class Employee as abstract class.

50 Employee.java 23 // return first name 24 public String getFirstName()
{ return firstName; } 28 // set last name public void setLastName( String last ) { lastName = last; } 34 // return last name public String getLastName() { return lastName; } 40 // set social security number public void setSocialSecurityNumber( String number ) { socialSecurityNumber = number; // should validate } 46 Employee.java

51 Employee.java Line 61 Abstract method overridden by subclasses.
// return social security number public String getSocialSecurityNumber() { return socialSecurityNumber; } 52 // return String representation of Employee object public String toString() { return getFirstName() + " " + getLastName() + "\nsocial security number: " + getSocialSecurityNumber(); } 59 // abstract method overridden by subclasses public abstract double earnings(); 62 63 } // end abstract class Employee Employee.java Line 61 Abstract method overridden by subclasses. Abstract method overridden by subclasses

52 Use superclass constructor for basic fields.
// Fig : SalariedEmployee.java // SalariedEmployee class extends Employee. 3 public class SalariedEmployee extends Employee { private double weeklySalary; 6 // constructor public SalariedEmployee( String first, String last, String socialSecurityNumber, double salary ) { super( first, last, socialSecurityNumber ); setWeeklySalary( salary ); } 14 // set salaried employee's salary public void setWeeklySalary( double salary ) { weeklySalary = salary < 0.0 ? 0.0 : salary; } 20 // return salaried employee's salary public double getWeeklySalary() { return weeklySalary; } 26 SalariedEmployee.java Line 11 Use superclass constructor for basic fields. Use superclass constructor for basic fields.

53 Must implement abstract method earnings.
// calculate salaried employee's pay; // override abstract method earnings in Employee public double earnings() { return getWeeklySalary(); } 33 // return String representation of SalariedEmployee object public String toString() { return "\nsalaried employee: " + super.toString(); } 39 40 } // end class SalariedEmployee Must implement abstract method earnings. SalariedEmployee.java Lines Must implement abstract method earnings.

54 HourlyEmployee.java 1 // Fig. 10.14: HourlyEmployee.java
2 // HourlyEmployee class extends Employee. 3 4 public class HourlyEmployee extends Employee { private double wage; // wage per hour private double hours; // hours worked for week 7 // constructor public HourlyEmployee( String first, String last, String socialSecurityNumber, double hourlyWage, double hoursWorked ) { super( first, last, socialSecurityNumber ); setWage( hourlyWage ); setHours( hoursWorked ); } 16 // set hourly employee's wage public void setWage( double wageAmount ) { wage = wageAmount < 0.0 ? 0.0 : wageAmount; } 22 // return wage public double getWage() { return wage; } 28 HourlyEmployee.java

55 Must implement abstract method earnings.
// set hourly employee's hours worked public void setHours( double hoursWorked ) { hours = ( hoursWorked >= 0.0 && hoursWorked <= ) ? hoursWorked : 0.0; } 35 // return hours worked public double getHours() { return hours; } 41 // calculate hourly employee's pay; // override abstract method earnings in Employee public double earnings() { if ( hours <= 40 ) // no overtime return wage * hours; else return 40 * wage + ( hours - 40 ) * wage * 1.5; } 51 // return String representation of HourlyEmployee object public String toString() { return "\nhourly employee: " + super.toString(); } 57 58 } // end class HourlyEmployee HourlyEmployee.java Lines Must implement abstract method earnings. Must implement abstract method earnings.

56 CommissionEmployee.java 1 // Fig. 10.15: CommissionEmployee.java
// CommissionEmployee class extends Employee. 3 public class CommissionEmployee extends Employee { private double grossSales; // gross weekly sales private double commissionRate; // commission percentage 7 // constructor public CommissionEmployee( String first, String last, String socialSecurityNumber, double grossWeeklySales, double percent ) { super( first, last, socialSecurityNumber ); setGrossSales( grossWeeklySales ); setCommissionRate( percent ); } 17 // set commission employee's rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } 23 // return commission employee's rate public double getCommissionRate() { return commissionRate; } CommissionEmployee.java

57 Must implement abstract method earnings.
29 // set commission employee's weekly base salary public void setGrossSales( double sales ) { grossSales = sales < 0.0 ? 0.0 : sales; } 35 // return commission employee's gross sales amount public double getGrossSales() { return grossSales; } 41 // calculate commission employee's pay; // override abstract method earnings in Employee public double earnings() { return getCommissionRate() * getGrossSales(); } 48 // return String representation of CommissionEmployee object public String toString() { return "\ncommission employee: " + super.toString(); } 54 55 } // end class CommissionEmployee CommissionEmployee.java Lines Must implement abstract method earnings. Must implement abstract method earnings.

58 1 // Fig. 10.16: BasePlusCommissionEmployee.java
2 // BasePlusCommissionEmployee class extends CommissionEmployee. 3 4 public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary; // base salary per week 6 // constructor public BasePlusCommissionEmployee( String first, String last, String socialSecurityNumber, double grossSalesAmount, double rate, double baseSalaryAmount ) { super( first, last, socialSecurityNumber, grossSalesAmount, rate ); setBaseSalary( baseSalaryAmount ); } 15 // set base-salaried commission employee's base salary public void setBaseSalary( double salary ) { baseSalary = salary < 0.0 ? 0.0 : salary; } 21 // return base-salaried commission employee's base salary public double getBaseSalary() { return baseSalary; } 27 BasePlusCommissionEmployee.java

59 Override method earnings in CommissionEmployee
// calculate base-salaried commission employee's earnings; // override method earnings in CommissionEmployee public double earnings() { return getBaseSalary() + super.earnings(); } 34 // return String representation of BasePlusCommissionEmployee public String toString() { return "\nbase-salaried commission employee: " + super.getFirstName() + " " + super.getLastName() + "\nsocial security number: " + super.getSocialSecurityNumber(); } 42 43 } // end class BasePlusCommissionEmployee Override method earnings in CommissionEmployee BasePlusCommissionEmployee.java Lines Override method earnings in CommissionEmployee

60 PayrollSystemTest.java 1 // Fig. 10.17: PayrollSystemTest.java
// Employee hierarchy test program. import java.text.DecimalFormat; import javax.swing.JOptionPane; 5 public class PayrollSystemTest { 7 public static void main( String[] args ) { DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 11 // create Employee array Employee employees[] = new Employee[ 4 ]; 14 // initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John", "Smith", " ", ); employees[ 1 ] = new CommissionEmployee( "Sue", "Jones", " ", 10000, .06 ); employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis", " ", 5000, .04, 300 ); employees[ 3 ] = new HourlyEmployee( "Karen", "Price", " ", 16.75, 40 ); 24 String output = ""; 26 PayrollSystemTest.java

61 Determine whether element is a BasePlusCommissionEmployee
// generically process each element in array employees for ( int i = 0; i < employees.length; i++ ) { output += employees[ i ].toString(); 30 // determine whether element is a BasePlusCommissionEmployee if ( employees[ i ] instanceof BasePlusCommissionEmployee ) { 33 // downcast Employee reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee currentEmployee = ( BasePlusCommissionEmployee ) employees[ i ]; 38 double oldBaseSalary = currentEmployee.getBaseSalary(); output += "\nold base salary: $" + oldBaseSalary; 41 currentEmployee.setBaseSalary( 1.10 * oldBaseSalary ); output += "\nnew base salary with 10% increase is: $" + currentEmployee.getBaseSalary(); 45 } // end if 47 output += "\nearned $" + employees[ i ].earnings() + "\n"; 49 } // end for 51 PayrollSystemTest.java Line 32 Determine whether element is a BasePlusCommissionEmployee Line 37 Downcast Employee reference to BasePlusCommissionEmployee reference Determine whether element is a BasePlusCommissionEmployee Downcast Employee reference to BasePlusCommissionEmployee reference

62 Get type name of each object in employees array
for ( int j = 0; j < employees.length; j++ ) output += "\nEmployee " + j + " is a " + employees[ j ].getClass().getName(); 56 JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); 59 } // end main 61 62 } // end class PayrollSystemTest Get type name of each object in employees array PayrollSystemTest.java Lines Get type name of each object in employees array

63 10.8 Örnek Uygulama: Arabirim (Interface) Oluşturma ve Kullanma
Arabirim (interface) : Shape Soyut sınıf Shape yerine arayüz yazalım Arabirim interface anahtar kelimesi ile tanıma başlanır. Arabirim yazım olarak sınıflara benzerler ancak örnek değişkenleri yoktur ve bildirilen metotların da gövdesi yoktur. Sınıflar arabirimi implement anahtar kelimesi ile kendilerine dahil ederler. public abstract metodlar içerirler. Sınıflar arabirim metodlarını uygulama zorunlulukları vardır.

64 Classes that implement Shape must implement these methods
// Fig : Shape.java // Shape interface declaration. 3 public interface Shape { public double getArea(); // calculate area public double getVolume(); // calculate volume public String getName(); // return shape name 8 } // end interface Shape Classes that implement Shape must implement these methods Shape.java Lines 5-7 Classes that implement Shape must implement these methods

65 Point.java Line 4 Point implements interface Shape
// Fig : Point.java // Point class declaration implements interface Shape. 3 public class Point extends Object implements Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair 7 // no-argument constructor; x and y default to 0 public Point() { // implicit call to Object constructor occurs here } 13 // constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } 21 // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation } 27 Point implements interface Shape Point.java Line 4 Point implements interface Shape

66 Point.java 28 // return x from coordinate pair 29 public int getX()
{ return x; } 33 // set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation } 39 // return y from coordinate pair public int getY() { return y; } 45 Point.java

67 Point.java Lines 47-59 Implement methods specified by interface Shape
// declare abstract method getArea public double getArea() { return 0.0; } 51 // declare abstract method getVolume public double getVolume() { return 0.0; } 57 // override abstract method getName to return "Point" public String getName() { return "Point"; } 63 // override toString to return String representation of Point public String toString() { return "[" + getX() + ", " + getY() + "]"; } 69 70 } // end class Point Implement methods specified by interface Shape Point.java Lines Implement methods specified by interface Shape

68 InterfaceTest.java Line 23 Create Shape array
// Fig : InterfaceTest.java // Test Point, Circle, Cylinder hierarchy with interface Shape. import java.text.DecimalFormat; import javax.swing.JOptionPane; 5 public class InterfaceTest { 7 public static void main( String args[] ) { // set floating-point number format DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 12 // create Point, Circle and Cylinder objects Point point = new Point( 7, 11 ); Circle circle = new Circle( 22, 8, 3.5 ); Cylinder cylinder = new Cylinder( 20, 30, 3.3, ); 17 // obtain name and string representation of each object String output = point.getName() + ": " + point + "\n" + circle.getName() + ": " + circle + "\n" + cylinder.getName() + ": " + cylinder + "\n"; 22 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array 24 InterfaceTest.java Line 23 Create Shape array Create Shape array

69 25 // aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = point; 27 // aim arrayOfShapes[ 1 ] at subclass Circle object arrayOfShapes[ 1 ] = circle; 30 // aim arrayOfShapes[ 2 ] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder; 33 // loop through arrayOfShapes to get name, string // representation, area and volume of every Shape in array for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + arrayOfShapes[ i ].toString() + "\nArea = " + twoDigits.format( arrayOfShapes[ i ].getArea() ) + "\nVolume = " + twoDigits.format( arrayOfShapes[ i ].getVolume() ); } 43 JOptionPane.showMessageDialog( null, output ); // display output 45 System.exit( 0 ); 47 } // end main 49 50 } // end class InterfaceTest InterfaceTest.java Lines Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array. Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array

70 InterfaceTest.java

71 10.8 Örnek Uygulama: Arayüz (Interface) Oluşturma ve Kullanma (devam)
Çoklu arabirim (interface) uygulaması implements anahtar sözcüğünden sonra arayüzler virgülle ayrılarak ard arda yazılabilir. Arabirimlerle sabitler tanımlama public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; }

72 10.9 İçiçe Sınıflar Üst düzey sınıflar İçiçe sınıflar
Bir sınıf yada metod içinde tanımlanmazlar. İçiçe sınıflar Başka sınıfın içinde tanımlanırlar. İç sınıflar Statik olmayan içiçe sınıflar

73 Time.java 1 // Fig. 10.21: Time.java
// Time class declaration with set and get methods. import java.text.DecimalFormat; 4 public class Time { private int hour; // private int minute; // private int second; // 9 // one formatting object to share in toString and toUniversalString private static DecimalFormat twoDigits = new DecimalFormat( "00" ); 12 // Time constructor initializes each instance variable to zero; // ensures that Time object starts in a consistent state public Time() { this( 0, 0, 0 ); // invoke Time constructor with three arguments } 19 // Time constructor: hour supplied, minute and second defaulted to 0 public Time( int h ) { this( h, 0, 0 ); // invoke Time constructor with three arguments } 25 Time.java

74 26 // Time constructor: hour and minute supplied, second defaulted to 0
public Time( int h, int m ) { this( h, m, 0 ); // invoke Time constructor with three arguments } 31 // Time constructor: hour, minute and second supplied public Time( int h, int m, int s ) { setTime( h, m, s ); } 37 // Time constructor: another Time3 object supplied public Time( Time time ) { // invoke Time constructor with three arguments this( time.getHour(), time.getMinute(), time.getSecond() ); } 44 // Set Methods // set a new time value using universal time; perform // validity checks on data; set invalid values to zero public void setTime( int h, int m, int s ) { setHour( h ); // set the hour setMinute( m ); // set the minute setSecond( s ); // set the second } 54 Time.java

75 Time.java 55 // validate and set hour 56 public void setHour( int h )
{ hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } 60 // validate and set minute public void setMinute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } 66 // validate and set second public void setSecond( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } 72 // Get Methods // get hour value public int getHour() { return hour; } 79 Time.java

76 Time.java Lines 101-107 Override method java.lang.Object.toString
// get minute value public int getMinute() { return minute; } 85 // get second value public int getSecond() { return second; } 91 // convert to String in universal-time format public String toUniversalString() { return twoDigits.format( getHour() ) + ":" + twoDigits.format( getMinute() ) + ":" + twoDigits.format( getSecond() ); } 99 // convert to String in standard-time format public String toString() { return ( ( getHour() == 12 || getHour() == 0 ) ? : getHour() % 12 ) + ":" + twoDigits.format( getMinute() ) + ":" + twoDigits.format( getSecond() ) + ( getHour() < 12 ? " AM" : " PM" ); } 108 109 } // end class Time Time.java Lines Override method java.lang.Object.toString Override method java.lang.Object.toString

77 JFrame provides basic window attributes and behaviors
1 // Fig : TimeTestWindow.java 2 // Inner class declarations used to create event handlers. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class TimeTestWindow extends JFrame { private Time time; private JLabel hourLabel, minuteLabel, secondLabel; private JTextField hourField, minuteField, secondField, displayField; private JButton exitButton; 12 // set up GUI public TimeTestWindow() { // call JFrame constructor to set title bar string super( "Inner Class Demonstration" ); 18 time = new Time(); // create Time object 20 // use inherited method getContentPane to get window's content pane Container container = getContentPane(); container.setLayout( new FlowLayout() ); // change layout 24 // set up hourLabel and hourField hourLabel = new JLabel( "Set Hour" ); hourField = new JTextField( 10 ); container.add( hourLabel ); container.add( hourField ); 30 JFrame provides basic window attributes and behaviors TimeTestWindow.java Line 7 JFrame provides basic window attributes and behaviors Line 17 JFrame (unlike JApplet) has constructor Line 19 Instantiate Time object JFrame (unlike JApplet) has constructor Instantiate Time object

78 Instantiate object of inner-class that implements ActionListener
// set up minuteLabel and minuteField minuteLabel = new JLabel( "Set Minute" ); minuteField = new JTextField( 10 ); container.add( minuteLabel ); container.add( minuteField ); 36 // set up secondLabel and secondField secondLabel = new JLabel( "Set Second" ); secondField = new JTextField( 10 ); container.add( secondLabel ); container.add( secondField ); 42 // set up displayField displayField = new JTextField( 30 ); displayField.setEditable( false ); container.add( displayField ); 47 // set up exitButton exitButton = new JButton( "Exit" ); container.add( exitButton ); 51 // create an instance of inner class ActionEventHandler ActionEventHandler handler = new ActionEventHandler(); 54 TimeTestWindow.java Line 53 Instantiate object of inner-class that implements ActionListener. Instantiate object of inner-class that implements ActionListener

79 Register ActionEventHandler with GUI components
// register event handlers; the object referenced by handler // is the ActionListener, which contains method actionPerformed // that will be called to handle action events generated by // hourField, minuteField, secondField and exitButton hourField.addActionListener( handler ); minuteField.addActionListener( handler ); secondField.addActionListener( handler ); exitButton.addActionListener( handler ); 63 } // end constructor 65 // display time in displayField public void displayTime() { displayField.setText( "The time is: " + time ); } 71 // launch application: create, size and display TimeTestWindow; // when main terminates, program continues execution because a // window is displayed by the statements in main public static void main( String args[] ) { TimeTestWindow window = new TimeTestWindow(); 78 window.setSize( 400, 140 ); window.setVisible( true ); 81 } // end main TimeTestWindow.java Lines Register ActionEventHandler with GUI components. Register ActionEventHandler with GUI components

80 Declare inner class that implements ActionListener interface
// inner class declaration for handling JTextField and JButton events private class ActionEventHandler implements ActionListener { 86 // method to handle action events public void actionPerformed( ActionEvent event ) { // user pressed exitButton if ( event.getSource() == exitButton ) System.exit( 0 ); // terminate the application 93 // user pressed Enter key in hourField else if ( event.getSource() == hourField ) { time.setHour( Integer.parseInt( event.getActionCommand() ) ); hourField.setText( "" ); } 100 // user pressed Enter key in minuteField else if ( event.getSource() == minuteField ) { time.setMinute( Integer.parseInt( event.getActionCommand() ) ); minuteField.setText( "" ); } 107 Declare inner class that implements ActionListener interface TimeTestWindow.java Line 85 Declare inner class Line 88 Must implement method actionPerformed Line 88 When user presses button or key, method actionPerformed is invoked Lines Determine action depending on where event originated When user presses JButton or Enter key, method actionPerformed is invoked Must implement method actionPerformed of ActionListener Determine action depending on where event originated

81 TimeTestWindow.java 108 // user pressed Enter key in secondField
else if ( event.getSource() == secondField ) { time.setSecond( Integer.parseInt( event.getActionCommand() ) ); secondField.setText( "" ); } 114 displayTime(); // call outer class's method 116 } // end method actionPerformed 118 } // end inner class ActionEventHandler 120 121 } // end class TimeTestWindow TimeTestWindow.java

82 TimeTestWindow.java

83 10.9 İçiçe Sınıflar (devam.)
İsimsiz içiçe sınıflar Bir sınıfın metodu içinde tanımlanırlar. İsimleri yoktur.

84 TimeTestWindow.java 1 // Fig. 10.23: TimeTestWindow2.java
// Demonstrating the Time class set and get methods import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class TimeTestWindow2 extends JFrame { private Time time; private JLabel hourLabel, minuteLabel, secondLabel; private JTextField hourField, minuteField, secondField, displayField; 11 // constructor public TimeTestWindow2() { // call JFrame constructor to set title bar string super( "Anonymous Inner Class Demonstration" ); 17 time = new Time(); // create Time object createGUI(); // set up GUI registerEventHandlers(); // set up event handling } 22 // create GUI components and attach to content pane private void createGUI() { Container container = getContentPane(); container.setLayout( new FlowLayout() ); 28 TimeTestWindow.java

85 TimeTestWindow.java 29 hourLabel = new JLabel( "Set Hour" );
hourField = new JTextField( 10 ); container.add( hourLabel ); container.add( hourField ); 33 minuteLabel = new JLabel( "Set minute" ); minuteField = new JTextField( 10 ); container.add( minuteLabel ); container.add( minuteField ); 38 secondLabel = new JLabel( "Set Second" ); secondField = new JTextField( 10 ); container.add( secondLabel ); container.add( secondField ); 43 displayField = new JTextField( 30 ); displayField.setEditable( false ); container.add( displayField ); 47 } // end method createGUI 49 // register event handlers for hourField, minuteField and secondField private void registerEventHandlers() { TimeTestWindow.java

86 Define anonymous inner class that implements ActionListener
// register hourField event handler hourField.addActionListener( 55 new ActionListener() { // anonymous inner class 57 public void actionPerformed( ActionEvent event ) { time.setHour( Integer.parseInt( event.getActionCommand() ) ); hourField.setText( "" ); displayTime(); } 65 } // end anonymous inner class 67 ); // end call to addActionListener for hourField 69 // register minuteField event handler minuteField.addActionListener( 72 new ActionListener() { // anonymous inner class 74 public void actionPerformed( ActionEvent event ) { time.setMinute( Integer.parseInt( event.getActionCommand() ) ); minuteField.setText( "" ); displayTime(); } Define anonymous inner class that implements ActionListener Pass ActionListener as argument to GUI component’s method addActionListener TimeTestWindow.java Line 54 Pass Action-Listener to GUI component’s method addAction-Listener Line 56 Define anonymous inner class Lines Inner class implements method actionPerformed Lines Repeat process for minuteField Inner class implements method actionPerformed of ActionListener Repeat process for JTextField minuteField

87 Repeat process for JTextField secondField
82 } // end anonymous inner class 84 ); // end call to addActionListener for minuteField 86 secondField.addActionListener( 88 new ActionListener() { // anonymous inner class 90 public void actionPerformed( ActionEvent event ) { time.setSecond( Integer.parseInt( event.getActionCommand() ) ); secondField.setText( "" ); displayTime(); } 98 } // end anonymous inner class 100 ); // end call to addActionListener for secondField 102 } // end method registerEventHandlers 104 // display time in displayField public void displayTime() { displayField.setText( "The time is: " + time ); } TimeTestWindow.java Line Repeat process for JTextField secondField Repeat process for JTextField secondField

88 110 // create TimeTestWindow2 object, register for its window events // and display it to begin application's execution public static void main( String args[] ) { TimeTestWindow2 window = new TimeTestWindow2(); 116 // register listener for windowClosing event window.addWindowListener( 119 // anonymous inner class for windowClosing event new WindowAdapter() { 122 // terminate application when user closes window public void windowClosing( WindowEvent event ) { System.exit( 0 ); } 128 } // end anonymous inner class 130 ); // end call to addWindowListener for window 132 window.setSize( 400, 105 ); window.setVisible( true ); 135 } // end main 137 138 } // end class TimeTestWindow2 TimeTestWindow.java Line Declare anonymous inner class that extends WindowsAdapter to enable closing of JFrame Declare anonymous inner class that extends WindowsAdapter to enable closing of JFrame

89 TimeTestWindow.java

90 10.9 İçiçe Sınıflar (devam)
İçiçe sınıflara için notlar: İçiçe sınıf içeren sınıfın derlenmesi Ayrı .class uzantılı dosyalarda derleme sonuçlanır. İç sınıf aşağıdaki gibi tanımlanır; public, protected, private or package access Access outer class’s this reference OuterClassName.this Outer class is responsible for creating inner class objects Nested classes can be declared static

91 10.10 Type-Wrapper Classes for Primitive Types
Each primitive type has one Character, Byte, Integer, Boolean, etc. Enable to represent primitive as Object Primitive types can be processed polymorphically Declared as final Many methods are declared static


"Bölüm 10 –Polimorfizm Outline 10.1 Polimorfizm" indir ppt

Benzer bir sunumlar


Google Reklamları