Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Abstraction (computer science) wikipedia , lookup
Falcon (programming language) wikipedia , lookup
Java syntax wikipedia , lookup
Design Patterns wikipedia , lookup
Java (programming language) wikipedia , lookup
Java performance wikipedia , lookup
Java ConcurrentMap wikipedia , lookup
Name mangling wikipedia , lookup
Object-oriented programming wikipedia , lookup
Class (computer programming) wikipedia , lookup
Inheritance What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes can inherit variables and methods (operations) from other classes. The inheriting class can then add extra attributes and/or methods of its own. What is the purpose of inheritance? Extend the functionality of an existing class. Share the commonality between two or more classes . Clerk Java Programming page 1 Employee Manager Receptionist 769822338 Example class BankAccount { private double balance; public double balance; // other member functions } class ChequeAccount extends BankAccount { public void WriteCheque (double amount) { //... } // other member functions } In the above example, ChequeAccount inherits from BankAccount. We can say that ChequeAccount is a subclass or derived class of BankAccount and BankAccount is called a super class or base class. Multiple inheritance is not allowed in Java. i.e. A subclass cannot inherit from more than one super classes. Java Programming page 2 769822338 A subclass can override a method in the super class. // Override.java Sample Run class Base { public int f() { return 10; } public int g() { return 10; } } $ java Override b.f() : 10 b.g() : 10 d.f() : 999 d.g() : 10 class Derived extends Base { public int f() { return 999; } } public class Override { public static void main(String[] args) { Base b = new Base(); Derived d = new Derived(); System.out.println("b.f() System.out.println("b.g() System.out.println("d.f() System.out.println("d.g() : : : : " " " " + + + + b.f()); b.g()); d.f()); d.g()); } } Java Programming page 3 769822338 Invoke Super Class Methods Sometimes a subclass may need to call the overridden method in the super class. To do this, Java provides the keyword super which references to the immediate super class. // CallSuper.java Sample Run class Base { public void f() { System.out.println("Base f is called."); } } $ java CallSuper Base f is called. Derived f is called. Base f is called. class Derived extends Base { public void f() { super.f(); System.out.println("Derived f is called."); super.f(); } } public class CallSuper { public static void main(String[] args) { Derived d = new Derived(); d.f(); } } Java Programming page 4 769822338 Abstract Classes There are many situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes. For instance, we could have an abstract superclass shape and derive concrete classes (non-abstract classes) such as square, circle, triangle etc. A class is made abstract by declaring it with the keyword abstract. abstract public class shape { String name; abstract public double area(); public String name() { return name; } //other stuff } // abstract method An abstract class cannot be instaniated. An abstract method has no method body. It is not legal to define an abstract method in a concrete class. Java Programming page 5 769822338 Base Class Access Control We have already known that the public and private controls. Inheritance introduces another access control specifier: protected. Declaring a member protected means that it is accessible only to methods of the same class, derived classes, classes in same package but not to others. Example class Super { public void void protected void private void } Public(){} Friendly(){} Protected(){} Private(){} class SubClass extends Super { void f() { Public(); Friendly(); Protected(); Private(); // error!! } } Java Programming page 6 769822338 // cont. class ClassInSamePackage { void f() { Public(); Friendly(); Protected(); Private(); // error!! } } class AnyOtherClass extends Super { void f() { Public(); Friendly(); // error!! Protected(); Private(); // error!! } } Java Programming page 7 769822338 Polymorphism Polymorphism enables us to write programs in a general fashion to handle a wide variety of existing and yet-to-be-specified related classes. Consider the following example, Appliance is a base class which has an On() method. that is overriden in each of its subclasses. Class Appliance { public void On() { //... } //... } Class VCR extends Appliance { public void On() { //... turn VCR on } } Class TV extends Appliance { public void On() { //... turn TV on } } Java Programming page 8 769822338 It is legal to assign a subclass object to a reference to base class. i.e. you can write Appliance a = new TV(); // assign a TV object to Appliance When you call a.On(), Java promises to invoke the correct version of On(). i.e. The method of actual object that a references to. Therefore TV.On() will be called. This is called dynamic method binding or late binding. We can use the following method AllOn() to turn on all appliances: public void AllOn(Appliance[] a) { for (int i=1; i<a.length; i++) a[i].On(); } public static void main(String[] args) { Appliance a[] = { new TV(), new VCR() }; // ... AllOn(a); // Turn on appliance on } Java Programming page 9 769822338 With polymorphism, it becomes possible to design and implement systems that are more easily extensible. Program can be written to process objects of types that may not exist when the program is under development. For example, if you bought a new Hi Fi and want to use the method to turn the new Hi Fi on, all you have to do is to write a new class HiFi which inherits from Appliance and overrides the method On(). Class HiFi extends Appliance { public void On() { //... turn TV on } } public static void main(String[] args) { Appliance a[] = { new TV(), new VCR(), new HiFi() }; // ... AllOn(a); // Turn on appliance on } Java Programming page 10 769822338 Example: Employee Hierarchy // Polymorphism.java // Abstract base class Employee abstract class Employee { private String firstName; private String lastName; // Constructor public Employee( String first, String last ) { firstName = new String ( first ); lastName = new String( last ); } // Return a copy of the first name public String getFirstName() { return new String( firstName ); } // Return a copy of the last name public String getLastName() { return new String( lastName ); } // Abstract method that must be implemented for each // derived class of Employee from which objects // are instantiated. abstract double earnings(); } Java Programming page 11 769822338 // Boss class derived from Employee final class Boss extends Employee { private double weeklySalary; // Constructor for class Boss public Boss( String first, String last, double s) { super( first, last ); // call base-class constructor setWeeklySalary( s ); } // Set the Boss's salary public void setWeeklySalary( double s ) { weeklySalary = ( s > 0 ? s : 0 ); } // Get the Boss's pay public double earnings() { return weeklySalary; } // Print the Boss's name public String toString() { return "Boss: " + getFirstName() + ' ' + getLastName(); } } Java Programming page 12 769822338 // CommissionWorker class derived from Employee final class CommissionWorker extends Employee { private double salary; // base salary per week private double commission; // amount per item sold private int quantity; // total items sold for week // Constructor for class CommissionWorker public CommissionWorker( String first, String last, double s, double c, int q) { super( first, last ); // call base-class constructor setSalary( s ); setCommission( c ); setQuantity( q ); } // Set CommissionWorker's weekly base salary public void setSalary( double s ) { salary = ( s > 0 ? s : 0 ); } // Set CommissionWorker's commission public void setCommission( double c ) { commission = ( c > 0 ? c : 0 ); } // Set CommissionWorker's quantity sold public void setQuantity( int q ) { quantity = ( q > 0 ? q : 0 ); } Java Programming page 13 769822338 // Determine CommissionWorker's earnings public double earnings() { return salary + commission * quantity; } // Print the CommissionWorker's name public String toString() { return "Commission worker: " + getFirstName() + ' ' + getLastName(); } } // Definition of class HourlyWorker final class HourlyWorker extends Employee { private double wage; // wage per hour private double hours; // hours worked for week // Constructor for class HourlyWorker public HourlyWorker( String first, String last, double w, double h ) { super( first, last ); // call base-class constructor setWage( w ); setHours( h ); } Java Programming page 14 769822338 // Set the wage public void setWage( double w ) { wage = ( w > 0 ? w : 0 ); } // Set the hours worked public void setHours( double h ) { hours = ( h >= 0 && h < 168 ? h : 0 ); } // Get the HourlyWorker's pay public double earnings() { return wage * hours; } public String toString() { return "Hourly worker: " + getFirstName() + ' ' + getLastName(); } } // Driver for Employee hierarchy class Test { public static void main(String[] args) { Employee[] ref = new Employee[3]; Boss b; CommissionWorker c; HourlyWorker h; Java Programming page 15 // base-class reference 769822338 b = new Boss( "John", "Smith", 800.00 ); c = new CommissionWorker( "Sue", "Jones", 400.0, 3.0, 150); h = new HourlyWorker( "Karen", "Price", 13.75, 40 ); ref[0] = b; ref[1] = c; ref[2] = h; // superclass reference to subclass object // superclass reference to subclass object // superclass reference to subclass object for (int i=0; i< ref.length; i++) System.out.println(ref[i].toString() + " earned $" + ref[i].earnings() ); } } Sample Run $ java Test Boss: John Smith earned $800 Commission worker: Sue Jones earned $850 Hourly worker: Karen Price earned $550 Java Programming page 16 769822338 Casting It is possible to cast from a base class to a subclass; however, an explicit cast is required: Appliance a = new TV(); // it is allowed TV b = (TV) a; // it is checked; may generate an exception To get rid of the possible exception thrown, you can use the instanceof operator to verify the actual type of a reference: Appliance a = new TV(); // it is allowed if (a instanceof TV) TV b = (TV) a; // now is safe Java Programming page 17 769822338 Interfaces Java does not support multiple inheritance: a class can be have more than one super class. However, Java provides a concept similar to the class, called interface to enable multiple inheritance. An interface is a collection of abstract methods. With an interface, all methods are public and abstract, and all data members are implicitly final, public and static. (i.e. they are constants). interface Recordable { void Record(); void Play(); } class TV_VCR extends TV implements Recordable { void Record(); void Play(); //...... } Java Programming page 18 769822338