Top Banner
Method signature • Name and parameter list public 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.
41

Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

Jan 02, 2016

Download

Documents

Beatrice Eaton
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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.

Page 2: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 3: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.
Page 4: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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); }}

Page 5: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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(); }}

Page 6: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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;}

Page 7: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 8: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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; }…}

Page 9: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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); } }

Page 10: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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); } }

Page 11: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 12: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 13: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

Java Programming: Program Design Including Data Structures 13

Some Constructors and Methods of the class Object

Page 14: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

Java Programming: Program Design Including Data Structures 14

Hierarchy of Java Stream Classes

Page 15: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 16: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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 );}}

Page 17: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 18: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 19: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 20: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 21: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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();

Page 22: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

State of the roster Array

The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.

Page 23: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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.

Page 24: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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++; }}

Page 25: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

Implementation Student in JavaCase Study

• See Poly example class student

Page 26: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

upcast

• Shape s = new Circle();

Page 27: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 28: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 29: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

• http://www.youtube.com/watch?v=0xw06loTm1k

Page 30: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 31: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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();

Page 32: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 33: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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()); } . . .}

Page 34: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

• 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

Page 35: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 36: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 37: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

Employee hierarchy UML class diagram

Page 38: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 39: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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

Page 40: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

// 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 );

Page 41: Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.

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");