Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | beatrice-eaton |
View: | 237 times |
Download: | 1 times |
Method signature
• Name and parameter listpublic static void test()public static int test() => Syntax error, Duplicate method test• You cannot declare more than one method with the same
name and the same number and type of arguments - the compiler cannot tell them apart.
• The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Protected Members of a Class
• Private members of a class are private to the class
• Cannot be directly accessed outside of class• Subclass cannot access• Private, public, protected• Protected allows subclass (only) access
class BaseClass { public int pubX = 10; private int privX = 10; protected int protX = 10; //Implicit Default Access Modifier int defX = 10; }
class DerivedClass extends BaseClass { public void test() { //System.out.println("privX = " + privX); System.out.println("pubX = " + pubX); System.out.println("protX = " + protX); System.out.println("defX = " + defX); }}
class TestClass {
public static void main(String[] args) { BaseClass b= new BaseClass(); DerivedClass d = new DerivedClass(); //System.out.println("b.privX = " + b.privX); System.out.println("b.publicX = " + b.pubX); System.out.println("b.protX = " + b.protX); System.out.println("b.defX = " + b.defX); d.test(); }}
DerivedClass
public void setData(int pub,int priv,int prot, int def){ super.setData(priv); //private in BaseClass protX = prot; //protected in BClass defX = def; //default in Dclass pubX = pub;}
Inheritance and Default Base Class Constructors
• Default constructor – run by default in Base class– Base class constructor is also run be subclass – unless you explicitly call a base class constructor– given it by default if you write no constructors)
• To call the base class constructor, use the keyword super
• A call to super must always be the first action taken in a constructor definition
public class Employee { protected String number; protected String name; public Employee (String num, String nam) { number = num; name = nam; }…….}
public class PartTimeEmployee extends Employee { private double hourlyPay; public PartTimeEmployee(String num, String name, double hPay) { super (num, nam); hourlyPay = hPay; }…}
Default constructor of super always called first
class Purple { protected int i = 0; public Purple() { System.out.println("Purple dc,i = " +i); } public Purple(int i) { this.i = i; System.out.println("Purple non dc,i = " +i); } }
class Violet extends Purple { Violet() { super(); //called whether or not we do this System.out.println("Violet dc,i = " +i); } Violet(int i) { super(i);//calls default if we don’t do this System.out.println("Violet non dc,i = " +i); } }
Constructor rules
public class Inheritance2 { public static void main(String[] args) { System.out.println("call Violet default constructor from client"); new Violet(); System.out.println("call Violet non-default constructor from client"); new Violet(4); } }
Java Programming: Program Design Including Data Structures
11
The class Object
• Directly or indirectly becomes the superclass of every class in Java
• Public members of class Object can be overridden/invoked by object of any class type
Java Programming: Program Design Including Data Structures 12
The class Object: Equivalent Definition of a Class
public class Clock{ //Declare instance variables as given in Chapter 8 //Definition of instance methods as given in Chapter 8 //...}
public class Clock extends Object{ //Declare instance variables as given in Chapter 8
//Definition of instance methods as given in Chapter 8 //...}
• Every class overrides toString, equals, copy constructor
Java Programming: Program Design Including Data Structures 13
Some Constructors and Methods of the class Object
Java Programming: Program Design Including Data Structures 14
Hierarchy of Java Stream Classes
Polymorphism• Reference of a superclass can point to its subclass• Shape s = new Shape();• Rectangle r = new Rectangle (10, 15);• s = r;• When a program invokes a method through a superclass variable, the
correct subclass version of the method is called, based on the type of the reference stored in the superclass variable
• s.area will invoke rectangles area• The same method name and signature can cause different actions to
occur, depending on the type of object on which the method is invoked• Facilitates adding new classes to a system with minimal modifications to
the system’s code• Especially useful with arrays
Demonstrating polymorphic behavior
public class Base{ protected int i= 100;... public void display() { System.out.println( i );} } public class Doubler extends Base { ...public void display() {System.out.println( i*2 );} } public class Tripler extends Base { ...public void display() {System.out.println(i*3 );} } public class Squarer extends Base { ...public void display() {System.out.println( i*i );}}
Static binding
Base B = new Base();B. display();
DoublerD = new Doubler();D. display();
Tripler T = new Tripler();T. display();
Squarer S = new Squarer();S. display();
100
200
300
10000
Polymorphic Behavior: Dynamic binding
• Superclass reference can be aimed at a subclass object
• This is possible because a subclass object is a superclass object as well
• When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called
Late binding - The appropriate version of a polymorphic method is decided at execution time
Base B = new Base();B. display();
Base D;D = new Doubler();D. display();
Base T;T = new Tripler();T. display();
Base S;S = new Squarer();S. display();
100
200
300
10000
Example: Inheritance Hierarchy of Class Student :Polymorphism case
Student#NUM_OF_TESTS : int = 3#name : string#test [] : int__________________________________+Student()+Student(in studentName : string)+setScore(in s1 : int, in s2 : int, in s3 : int)+setName(in newName : string)+getTestScore(int) : int+getCoursegrade() : string+setTestScore(in testNumber : int, in testName : string)+getName() : string+computeCourseGrade()
GraduateStudent
_________________________+computeCourseGrade()
_________________________UnderGraduateStudent
_________________________+computeCourseGrade()
Example: Inheritance Hierarchy of Class Student : Polymorphism caseCreating the roster
•an array must contain elements of the same data type. For example, we can’t store integers and real numbers in the same array. •To follow this rule, it seems necessary for us to declare two separate arrays, one for graduate and another for undergraduate students. This rule, however, does not apply when the array elements are objects using the polymorphism. We only need to declare a single array.
We can create the roster array combining objects from the Student, UndergraduateStudent, and GraduateStudent classes.Student roster = newStudent[40]; // this allocates space for 40 references. . .roster[0]= new GraduateStudent(); // this allocates space for the actual objectroster[1]= new UndergraduateStudent();roster[2]= new UndergraduateStudent();roster[3]= new GraduateStudent();
State of the roster Array
The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.
Sample Polymorphic Message
• To compute the course grade using the roster array, we executefor(inti = 0; i < numberOfStudents; i++) { roster[i].computeCourseGrade();}
• If roster[i] refers to a GraduateStudent, then the computeCourseGrademethod of the GraduateStudentclass is executed.
• If roster[i] refers to an UndergraduateStudent, then the computeCourseGrademethod of the UndergraduateStudentclass is executed.
The instanceof Operator
• The instanceof operator can help us learn the class of an object.• The following code counts the number of undergraduate students.int undergradCount= 0;for(int i = 0; i < numberOfStudents; i++) { if( roster[i] instanceof UndergraduateStudent) { undergradCount++; }}
Implementation Student in JavaCase Study
• See Poly example class student
upcast
• Shape s = new Circle();
Java Programming: Program Design Including Data Structures
27
Polymorphism (continued)
• Can declare a method of a class final using the keyword final
public final void doSomeThing(){
//...}
• If a method of a class is declared final, it cannot be overridden with a new definition in a derived class
Java Programming: Program Design Including Data Structures
28
Polymorphism (continued)
• Can also declare a class final using the keyword final
• If a class is declared final, then no other class can be derived from this class
• Java does not use late binding for methods that are private, marked final, or static
• http://www.youtube.com/watch?v=0xw06loTm1k
Abstract Class
• In order to postpone the definition of a method, Java allows an abstract method to be declared– An abstract method has a heading, but no method body– The body of the method is defined in the subclasses
• The class that contains an abstract method is called an abstract class
• Intended as a general description• Specify only what is common (attributes and
behaviors) among subclasses
Abstract Method
• An abstract method is like a placeholder for a method that will be fully defined in a descendent class
• It cannot be private• It has no method body, and ends with a semicolon
in place of its body• Constructors and static methods cannot be abstractpublic abstract double area();public abstract double perimeter();
Java Programming: Program Design Including Data Structures
32
Abstract Classes
• A class that is declared with the reserved word abstract in its heading
• An abstract class can contain instance variables, constructors, finalizers, and non-abstract methods
• An abstract class can contain abstract methods• If a class contains an abstract method, the class
must be declared abstract• You cannot instantiate an object of an abstract
class type; can only declare a reference variable of an abstract class type
• Can have several levels of abstract classes
33
Abstract Class Example
public abstract class Shape{ protected String color; . . . public abstract double area(); public abstract double perimeter(); public void display() { System.out.println(this.area()); System.out.println(this.perimeter()); } . . .}
• An abstract class can have any number of abstract and/or fully defined methods
• if a derived class of an abstract class adds to or does not define all of the abstract methods, then it is abstract also, and must add abstract to its modifier
• A class that has no abstract methods is called a concrete class
• Concrete class must give the definitions of all the abstract methods of the superclass
Pitfall: You Cannot Create Instances of an Abstract Class
• An abstract class can only be used to derive more specialized classes– While it may be useful to discuss shape in general,
in reality a shape must be a rectangle form or a square form
• An abstract class constructor cannot be used to create an object of the abstract class– However, a subclass constructor will include an
invocation of the abstract class constructor in the form of super
Dynamic Binding and Abstract Classes
• Controlling whether a subclass can override a superclass method– Field modifier final
• Prevents a method from being overridden by a subclass
– Field modifier abstract• Requires the subclass to override the method
• Early binding or static binding– The appropriate version of a method is decided at
compilation time– Used by methods that are final or static
Employee hierarchy UML class diagram
Example: Inheritance Hierarchy of Class (employee example)
Employee-fName : string-lName : string-ssn : string+Employee()+setFirstName(in fNa : string)+setLastName(in lName : string)+setSNN(in snn : string)+getFirstName() : string+getLastName() : string+getSNN() : string+earnings() : double+toString()
earnings toString
Employee abstract firstName lastNamesocialSecurityNumber
Salaried-Employee
weeklySalary firstName lastNamesocialSecurityNumberweeklySalary
Hourly-Employee
if( hours() <= 40 wage * hourselse 40 * wage + ( hours-40 ) * wage* 1.5
firstName lastNamesocialSecurityNumberhours, wage
Commission-Employee
commissionRate + grossSales firstName lastNamesocialSecurityNumbergrossSales, commissionRate
BasePlus-Commission-Employee
(commissionRate + grossSales) _ baseSalary
firstName lastNamesocialSecurityNumbergrossSales, commissionRate, baseSalary
// create objects of the concrete subclass SalariedEmployee sa= new SalariedEmployee("John", "Smith", "111-11-1111", 800.00 ); HourlyEmployee he = new HourlyEmployee( “Rob", "Jones", "222-22-2222", 16.75, 40 ); CommissionEmployee ce = new CommissionEmployee("Mike", "Adams", "333-33-3333", 10000, .06 ); BasePlusCommissionEmployee bp = new BasePlusCommissionEmployee("Beth", "Lake", "444-44-4444", 5000, .04, 300 );
System.out.println( "Employees processed individually:\n" ); /* sa is the same as sa.toString() */ System.out.println( sa + "\nearned: "+ sa.earnings()+"\n\n"); System.out.println( he + "\n earned: "+ he.earnings()+"\n\n"); System.out.println(ce + "\n earned: "+ ce.earnings()+"\n\n"); System.out.println(bp + "\n earned: "+ bp.earnings()+"\n\n");