• No results found

Syntax. Example. Example. A subclass inherits from a superclass using the extends keyword

N/A
N/A
Protected

Academic year: 2021

Share "Syntax. Example. Example. A subclass inherits from a superclass using the extends keyword"

Copied!
11
0
0

Loading.... (view fulltext now)

Full text

(1)

12/13/2004 Inheritance in Java 1

Syntax

• A subclass inherits from a superclass using the

extends

keyword

• Inheritance is applicable to top-level classes,

nested top-level classes, member classes, local

classes and anonymous classes

class subClassName extends superClassName {

variable and method declarations

}

12/13/2004 Inheritance in Java 2

Example

public class Employee { private String name; private int id; public String getName() {

return name; }

public int getId() { return id; } }

public class SalariedEmployee extends Employee { private int rate;

public int getRate() { return rate; }

}

public class HourlyEmployee extends Employee { private int rate;

private int hours; public int getRate() {

return rate; }

public int getHours() { return hours; }

}

Example

public class Payroll {

public static void main( String args[] ) { SalariedEmployee lisa = new SalariedEmployee(); HourlyEmployee james = new HourlyEmployee(); System.out.println( lisa.getName() ); System.out.println( lisa.getId() ); System.out.println( lisa.getRate() ); System.out.println( james.getName() ); System.out.println( james.getId() ); System.out.println( james.getRate() ); System.out.println( james.getHours() ); } }

(2)

12/13/2004 Inheritance in Java 4

Example

public class Payroll {

public static void printEmployeeInfo( Employee e ) { System.out.println( e.getName() ); System.out.println( e.getId() ); }

public static void main( String args[] ) { SalariedEmployee lisa = new SalariedEmployee(); HourlyEmployee james = new HourlyEmployee(); printEmployeeInfo( lisa ); System.out.println( lisa.getRate() ); printEmployeeInfo( james ); System.out.println( james.getRate() ); System.out.println( james.getHours() ); } } 12/13/2004 Inheritance in Java 5

Why Won’t This Work?

public class Payroll {

public static void printEmployeeInfo( Employee e ) { System.out.println( e.getName() ); System.out.println( e.getId() ); System.out.println( e.getRate() ); }

public static void main( String args[] ) { SalariedEmployee lisa = new SalariedEmployee(); HourlyEmployee james = new HourlyEmployee(); printEmployeeInfo( lisa ); System.out.println( lisa.getRate() ); printEmployeeInfo( james ); System.out.println( james.getRate() ); System.out.println( james.getHours() ); } }

Inheritance

• A class can inherit from any class that is not final.

• Objects of the subclass contain all the instance

variables and methods declared by the superclass.

• The accessibility rules are still enforced which

means a subclass cannot access the private parts of

the superclass.

• Subclassing can be repeated as many times as

desired. A class can have only one superclass, but

may have many subclasses.

(3)

12/13/2004 Inheritance in Java 7

Why Won’t This Work?

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { name = n;

id = i; rate = r; }

public int getRate() { return rate; }

}

12/13/2004 Inheritance in Java 8

Constructors and Inheritance

• The guarantee of proper initialization must be

maintained in the presence of inheritance.

– Unless specified, java will call the default constructors

for each class in the inheritance hierarchy

• Java provides syntax for explicitly controlling

which constructors are called.

• The keyword super can be used to explicitly call

a superclass constructor

– super ( argumentList ) ;

• super

must be the first statement in a constructor

Example

public class Employee { private String name; private int id;

public Employee( String n, int i ) { name = n;

id = i; }

public String getName() { return name; }

public int getId() { return id; } }

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { super( n, i ); rate = r; }

public int getRate() { return rate; }

(4)

12/13/2004 Inheritance in Java 10

Why Won’t This Compile?

public class Employee { private String name; private int id;

public Employee( String n, int i ) { name = n;

id = i; }

public String getName() { return name; }

public int getId() { return id; } }

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { rate = r;

}

public int getRate() { return rate; }

}

12/13/2004 Inheritance in Java 11

Protected

• Java provides a third access type called

protected

• Instance variables defines as protected can be

accessed

– By any subclass

– Or by classes defined within the same package

• Some feel that protected breaks encapsulation

– Make everything private

– Provide accessors and mutators if necessary

Example

public class Employee { protected String name; protected int id; public String getName() {

return name; }

public int getId() { return id; } }

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { name = n; id = = i; rate = r; }

public int getRate() { return rate; }

(5)

12/13/2004 Inheritance in Java 13

Scope Rules

• Inheritance increases the number of scopes that

need to be searched (both static and instance

declarations are searched)

– check the local scope and any local scopes

– check the class scope

– check each superclass scope in turn up to the top of the

inheritance chain

• If variables with the same identifier are declared in

several scopes, the first one found is used.

12/13/2004 Inheritance in Java 14

Method Overloading

• Methods can be overloaded, meaning that two or

methods in the same class can have the same name

provided they have different parameter lists.

• The return type for all overloaded methods must

be the same.

• In a class with an overloaded method, all versions

of the method are available

• Note that method overloading does not really have

anything to do with inheritance

Method Overriding

• A subclass can override an inherited method by

providing a new method declaration that has the

same name, the same number and types of

parameters and the same result type as the one

inherited.

• Only the overridden method is directly accessible

– The original method is still there, but you have to use

super

to access it

• Method overriding relies on dynamic binding, so

the type of the object determines which method

gets called.

(6)

12/13/2004 Inheritance in Java 16

Class Object

• Every class in Java inherits from the class Object

• Class Object declares the following methods that

can be overridden:

– public boolean equals( Object obj );

– public String toString();

– public final native int hashCode() ;

– protective native Object clone();

– protected void finalize();

– public final Class getClass()

12/13/2004 Inheritance in Java 17

Example

public class Employee { private String name; private int id; public Employee( String n,

int i ) { name = n; id = i; }

public String getName() { return name; }

public int getId() { return id; }

public String toString() { return name + ", " + id; }

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { super( n, i ); rate = r; }

public int getRate() { return rate; }

public String toString() { return getName() + ", " + getId() + ", " + rate; } }

Better Yet…

public class Employee { private String name; private int id; public Employee( String n,

int i ) { name = n; id = i; }

public String getName() { return name; }

public int getId() { return id; }

public String toString() { return name + ", " + id; }

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { super( n, i ); rate = r; }

public int getRate() { return rate; }

public String toString() { return super.toString() +

", " + rate; }

(7)

12/13/2004 Inheritance in Java 19

Did You Ever Wonder…

• Did you ever wonder how println() or

print()

work?

• println()

is an overloaded method

– void println(boolean x)

– void println(char x)

– void println(int x)

– void println(double x)

– void println(Object x)

• x.toString()!!!

12/13/2004 Inheritance in Java 20

computePay()

• For the Employee class we would like to add a

computePay()

method

• Where do we put it?

– Can’t put it in the Employee class since we don’t

know how to compute the pay for a generic employee

– We really don’t want to put it in the subclasses because

we won’t be able to say

• Employee x; x.computePay()

• What we really want is a placeholder in the

Employee

class and the method definition in the

sublcass

Abstract Methods

• A method can be declared abstract so that it must

be overridden by subclasses.

• An abstract class does not have a method body;

the declaration ends with a semi-colon not a

compound statement.

• A class declaring one or more abstract methods

must be declared as an abstract class

(8)

12/13/2004 Inheritance in Java 22

Abstract Classes

• An abstract class is a place holder for declaring

shared methods and variables for use by

subclasses.

• An abstract class cannot have instance objects and

so exists as a class that other classes can inherit

from.

• A concrete class is a class that is not abstract

12/13/2004 Inheritance in Java 23

computePay()

public abstract class Employee { private String name; private int id; public Employee( String n,

int i ) { name = n; id = i; }

public String getName() { return name; }

public int getId() { return id; }

public abstract int computePay();

public String toString() { return name + ", " + id; }

computePay()

public class SalariedEmployee extends Employee { private int rate;

public SalariedEmployee( String n, int i, int r ) { super( n, i ); rate = r; }

public int getRate() { return rate; }

public computePay() { return rate; }

public String toString() { return super.toString() +

", " + rate; }

(9)

12/13/2004 Inheritance in Java 25

Final Methods

• A final instance method cannot be overridden (but

can still be overloaded).

• A final static method cannot be re-declared in a

sublcass.

• Final methods prevent a method that has the same

name and parameter types from being declared in

a subclass.

• This takes into account both static and instance

variables.

12/13/2004 Inheritance in Java 26

Interfaces

• An interface declaration allows the specification

of a reference type without providing an

implementation.

• A type can conform to another type if it specifies

at least the same set of methods as the other type

(and possibly more).

• The two types do not have to be related by

inheritance which gives more freedom as to which

types may conform to other types.

Syntax

• An interface is declared as shown below:

• The optional modifier allows an interface to be

declared public.

• Any variables declared are implicitly constants

and are also static

interfaceModifier interface identifier {

interfaceMethodDeclarations;

interfaceVariableDeclarations;

(10)

12/13/2004 Inheritance in Java 28

Implements

• The implements keyword allows a class to

implement (or conform to) one or more interfaces.

• A class can implement any number of interfaces

(and also extend a class at the same time).

• Any variables defined in the interface become

static variables of the class.

• A method declared in a public interface must be

public in an implementing class.

12/13/2004 Inheritance in Java 29

Example

public interface Calculator { public int add( int x, int y ); public int sub( int x, int y ); public int mult( int x, int y ); public int div( int x, int y ); };

public class StandardCalculator implements Calculator { public int add( int x, int y ) { return x + y; } public int sub( int x, int y ) { return x - y; } public int mult( int x, int y ) { return x * y; } public int div( int x, int y ) { return x / y; } }

Example

public interface StatCalculator { public double avg( int[] x ); public double sum( int x[] ); public double std( int[] x ); }

public class CalculatorWithStats implements Calculator, StatCalculator { // public int add( int x, int y )…

// public int sub( int x, int y )… // public int mult( int x, int y )… // public int div( int x, int y )…

public double avg( int[] x ) { return sum( x ) / x.length; } public double sum( int[] x ) {

double s = 0;

for ( int i = 0; i < x.length; i++ ) { s = s + x[ i ]; } return s;

}

public double std( int[] x ) { double retVal = 0; if ( x.length > 1 ) {

double sumDiff = 0; double average = avg( x ); for ( int i = 0; i < x.length; i++ ) {

double diff = x[ i ] - average; sumDiff = sumDiff + diff * diff; }

retVal = Math.sqrt( sumDiff / ( x.length - 1 ) ); }

(11)

12/13/2004 Inheritance in Java 31

Example

public class CalculatorWithStats extends StandardCalculator implements StatCalculator { public double avg( int[] x ) { return sum( x ) / x.length; }

public double sum( int[] x ) { double s = 0;

for ( int i = 0; i < x.length; i++ ) { s = s + x[ i ]; } return s;

}

public double std( int[] x ) { double retVal = 0; if ( x.length > 1 ) {

double sumDiff = 0; double average = avg( x ); for ( int i = 0; i < x.length; i++ ) {

double diff = x[ i ] - average; sumDiff = sumDiff + diff * diff; }

retVal = Math.sqrt( sumDiff / ( x.length - 1 ) ); } return retVal; } } 12/13/2004 Inheritance in Java 32

Example

public interface StatCalculator extends Calculator { public double avg( int[] x );

public double sum( int x[] ); public double std( int[] x ); }

References

Related documents

(40 mg/mL) to overnight culture of Gram-negative bacteria (Pseudomonas aeruginosa and Escherichia coli) and Gram- positive bacteria (Enterococcus faecalis and Staphylococcus..

public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1254. Socket s1 =

The wellbore characteristics affecting completion con- figuration or component selection are best summarized by reviewing the drilling, evaluation and pre-completion activities

public static void main(String [] args) throws Exception { Configuration conf = new Configuration();. String[] otherArgs = new GenericOptionsParser(conf,

SANDVIK CNMA 12 04 08 H1P (uncoated carbide) inserts were used throughout. conventional emulsified mineral oil based flood cooling system was utilized. The three main

1995 Northeastern Forest Experiment Station and West Virginia University 1997 University of Missouri and the North Central Forest Experiment Station 1999 University of Kentucky and

public static void main (String[] args) {. Defines a method

Radical operations with lymph node dissection in patients with breast cancer are characterized by a high frequency of early postoperative complications, mainly associated