69
Java Sub and superclasses using extends

Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

  • View
    218

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Java

Sub and superclasses using extends

Page 2: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Subclass Constructors

• The following example illustrates how to use the super keyword to invoke a superclass's constructor.

• It is from java doc tutorials bicycle class example

Page 3: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Class bicyclepublic class Bicycle {

// the Bicycle class has three fields public int cadence; public int gear; public int speed;

// the Bicycle class has one constructor public Bicycle(int startCadence, int startSpeed,

int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }

// the Bicycle class has four methods

Page 4: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Methodspublic void setCadence(int newValue) { cadence = newValue; }

public void setGear(int newValue) { gear = newValue; }

public void applyBrake(int decrement) { speed -= decrement; }

public void speedUp(int increment) { speed += increment; }

}

Page 5: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

MountainBike subclass

• MountainBike is a subclass of Bicycle.

Page 6: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Subclass MountainBikepublic class MountainBike extends Bicycle {

// the MountainBike subclass adds one field public int seatHeight;

// the MountainBike subclass has one constructor public MountainBike(int startHeight, int

startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; }

// the MountainBike subclass adds one method public void setHeight(int newValue) { seatHeight = newValue; }

}

Page 7: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

• The MountainBike (subclass) constructor calls the superclass constructor and then adds initialization code of its own:

• public MountainBike(int startHeight, int startCadence, int

startSpeed, int startGear) { • super(startCadence, startSpeed, startGear);

seatHeight = startHeight; }

• Invocation of a superclass constructor must be the first line in the subclass constructor.

Page 8: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

The syntax for calling a superclass constructor is

• super(); --or-- super(parameter list);

• With super(), the superclass no-argument constructor is called.

• With super(parameter list), the superclass constructor with a matching parameter list is called.

Page 9: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Note

• Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

• If the super class does not have a no-argument constructor, you will get a compile-time error.

• Object does have such a constructor, so if Object is the only superclass, there is no problem.

Page 10: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Constructor chaining

• If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object.

• In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

Page 11: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Super

• Consider this class, Superclass:

• public class Superclass { • public void printMethod()

{ System.out.println("Printed in Superclass."); }

• }

Page 12: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Subclass

• Here is a subclass, called Subclass, that overrides printMethod():

• public class Subclass extends Superclass {

• public void printMethod() { //overrides printMethod in Superclass super.printMethod(); System.out.println("Printed in Subclass"); }

Page 13: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

How its used

• public static void main(String[] args) { • Subclass s = new Subclass(); • s.printMethod(); } • } • Within Subclass, the simple name printMethod() refers to

the one declared in Subclass, which overrides the one in Superclass.

• So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown.

• Compiling and executing Subclass prints the following: Printed in Superclass. Printed in Subclass

Page 14: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Class Modifiers

• So far we have seen many examples of such modifiers

• E.g.

• Public

• Abstract etc

Page 15: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Terminology

• Access Modifier– determines access rights for the class and its

members– defines where the class and its members can

be used

Page 16: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Class Modifiers

• A class declaration may include class modifiers. • ClassModifiers: ClassModifier ClassModifiers

ClassModifier ClassModifier: one of • public • protected • private • abstract • static • final

Page 17: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Field Modifiers

• FieldModifiers: • FieldModifier FieldModifiers • FieldModifier FieldModifier: one of • public • protected • private • static • final

Page 18: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Why use these

It is important in many applications to hide data from the programmer

E.g., a password program must be able to read in a password and

compare it to the current one or allow it to be changed

But the password should never be accessed directly!

• public class Password {

• public String my_password;

• :

• }

• Password ProtectMe;

• :

• ProtectMe.my_password = “backdoor”; // this is bad

Page 19: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Public etc

• public means that any class can access the data/methods

• private means that only the class can access the data/methods

• protected means that only the class and its subclasses can access the data/methods

Page 20: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Access Modifiers

Access Modifier Class or member can be referenced by…

public methods of the same class, and methods of other classes

private methods of the same class only

protected methods of the same class, methods of subclasses, and methods of classes in the same package

No access modifier (package access)

methods in the same package only

Page 21: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

public vs. private

• Classes are usually declared to be public

• Instance variables are usually declared to be private

• Methods that will be called by the client of the class are usually declared to be public

• Methods that will be called only by other methods of the class are usually declared to be private

Page 22: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

public

• Public access• Most liberal kind of access• Class or field is accessible everywhere• When a method or variable is labelled with the keyword public it

means that any other class or object can use that public method or variable

When a class is labelled with the keyword public, it means the class can be used by any other class

• The keyword private is used to restrict access and prevent inheritance!

Page 23: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Private

• Private if its only visible from inside the class definition

• This is compromised somewhat by public access methods

Page 24: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Example

• public class Secret {

• private String theSecret;

• private String getSecret (){

• ...

• }

• }

• Both theSecret and getSecret variables are only accessible inside the class

Page 25: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Consider

public class NotSoSecret extends Secret {

...

public void getSecret(){

super.getSecret();

...

}

}• You can’t access getSecret by inheritance

because its private

Page 26: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

• Secret mySecret;

• NotSoSecret myDiary;

• ...

• mySecret.getSecret();

• myDiary.getSecret();• Cannot invoke the getSecret method on mySecret since it’s private.

• Can invoke getSecret on myDiary because it’s public in class NotSoSecret

Page 27: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Class Modifiers

• A class declaration may include class modifiers. • ClassModifiers: ClassModifier ClassModifiers

ClassModifier ClassModifier: one of • public • protected • private • abstract • static • final

Page 28: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Defining Instance Variables

Syntax:

accessModifier dataType identifierList;

dataType can be primitive date type or a class type

identifierList can contain:– one or more variable names of the same data type

– multiple variable names separated by commas

– initial values

• Optionally, instance variables can be declared as final

Page 29: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Examples of Instance Variable Definitions

private String name = "";

private final int PERFECT_SCORE = 100,

PASSING_SCORE = 60;

private int startX, startY,

width, height;

Page 30: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Tips

• Define instance variables for the data that all objects will have in common.

• Define instance variables as private so that only the methods of the class will be able to set or change their values.

• Begin the identifier name with a lowercase letter and capitalize internal words.

Page 31: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

The Auto Class

public class Auto

{

private String model;

private int milesDriven;

private double gallonsOfGas;

}

Page 32: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Field Modifiers

• FieldModifiers: • FieldModifier FieldModifiers • FieldModifier FieldModifier: one of • public • protected • private • static • final

Page 33: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

static

• If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized

Page 34: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

static Variables

• Also called class variables • One copy of a static variable is created per class• static variables are not associated with an object• static constants are often declared as public• To define a static variable, include the keyword static in its

definition:• Syntax:

accessSpecifier static dataType variableName;

• Example:

public static int countAutos = 0;

Page 35: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

static Methods

• Also called class methods• Often defined to access and change static

variables• static methods cannot access instance

variables:– static methods are associated with the class, not

with any object.– static methods can be called before any object is

instantiated, so it is possible that there will be no instance variables to access.

Page 36: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Rules for static and Non-static Methods

• See Examples 7.12 and 7.13

static Method

Non-static Method

Access instance variables? no yes

Access static class variables? yes yes

Call static class methods? yes yes

Call non-static instance methods?

no yes

Use the object reference this? no yes

Page 37: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

final Fields

• A field can be declared final

• Both class and instance variables (static and non-static fields) may be declared final.

• Effectively final declares the variable to be constant

Page 38: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Example

private final int PERFECT_SCORE = 100,

Page 39: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

To stop a class• being inherited from (sub-classes) we can

declare it as a final class e.g.

If Person was declared as final

• final class Person {

• ...

• // the body of the class

• ...

• }

Page 40: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Then the following would not be allowed:

• class Programmer extends Person {

• ...

• // the body of the class

• ...

• }

Page 41: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Method Return Types

• The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void.

• Methods with a return type of void do not return a value to the caller.

Page 42: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Method Body• The code that performs the method's

function is written between the beginning and ending curly braces.

• Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body.

Page 43: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Methods continued

• In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

Page 44: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

main is a Method

public static void main( String [] args )

{

// application code

}

Let's look at main's API in detail:

public main can be called from outside the class. (The JVM calls main.)

static main can be called by the JVM without instantiating an object.

void main does not return a value

String [] args main's parameter is a String array

Page 45: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Value-Returning Methods

• Use a return statement to return the value

• Syntax: return expression;

Page 46: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Class Scope

• Instance variables have class scope– Any constructor or method of a class can

directly refer to instance variables.

• Methods also have class scope– Any method or constructor of a class can call

any other method of a class (without using an object reference).

Page 47: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Local Scope

• A method's parameters have local scope, meaning that: – a method can directly access its parameters.– a method's parameters cannot be accessed by

other methods.

• A method can define local variables which also have local scope, meaning that:– a method can access its local variables.– a method's local variables cannot be accessed by

other methods.

Page 48: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Summary of Scope

• A method in a class can access:– the instance variables of its class– any parameters sent to the method– any variable the method declares from the

point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first

– any methods in the class

Page 49: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Accessor Methods• Clients cannot directly access private

instance variables, so classes provide public accessor methods with this standard form:

public returnType getInstanceVariable( ) {

return instanceVariable;

}

(returnType is the same data type as the instance variable)

Page 50: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Accessor Methods

• Example: the accessor method for model.

public String getModel( )

{

return model; }

Page 51: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Mutator Methods

• Allow client to change the values of instance variables

public void setInstanceVariable(

dataType newValue )

{

// validate newValue,

// then assign to instance variable

}

Page 52: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Mutator Methods

• Example: the mutator method for milesDriven

public void setMilesDriven( int newMilesDriven )

{

if ( newMilesDriven >= 0 )

milesDriven = newMilesDriven;

else

{

System.err.println( "Miles driven "

+ "cannot be negative." );

System.err.println( "Value not changed." );

}

}

Page 53: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Data Manipulation Methods• Perform the "business" of the class.

• Example: a method to calculate miles per gallon:

public double calculateMilesPerGallon( )

{

if ( gallonsOfGas != 0.0 )

return milesDriven / gallonsOfGas;

else

return 0.0;

}

Page 54: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

The Object Reference this

• How does a method know which object's data to use?

• this is an implicit parameter sent to methods and is an object reference to the object for which the method was called.

• When a method refers to an instance variable name, this is implied• Thus:

variableName model

is understood to be is understood to be

this.variableName this.model

Page 55: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Using this in a Mutator Methodpublic void setInstanceVariable(

dataType instanceVariableName )

{

this.instanceVariableName = instanceVariableName;

}

• Example:public void setModel( String model )

{

this.model = model;

}

this.model refers to the instance variable.

model refers to the parameter.

Page 56: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

The toString Method

• Returns a String representing the data of an object

• Client can call toString explicitly by coding the method call.

Page 57: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Example

• Client can call toString implicitly by using an object reference where a String is expected.

• Example client code:

Auto compact = new Auto( );

// explicit toString call

System.out.println( compact.toString( ) );

// implicit toString call

System.out.println( compact );

Page 58: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

The toString API

Return value

Method name and argument list

String toString( )

returns a String representing the data of an object

Page 59: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Auto Class toString Method

public String toString( )

{

DecimalFormat gallonsFormat =

new DecimalFormat( "#0.0" );

return "Model: " + model

+ "; miles driven: " + milesDriven

+ "; gallons of gas: "

+ gallonsFormat.format( gallonsOfGas );

}

Page 60: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

The equals Method

• Determines if the data in another object is equal to the data in this objectReturn value Method name and argument list

boolean equals( Object obj )

returns true if the data in the Object obj is the same as in this object; false otherwise.

Page 61: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Example

• Example client code using Auto references auto1 and auto2:

if ( auto1.equals( auto2 ) )

System.out.println( "auto1 equals auto2" );

Page 62: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Auto Class equals Method

public boolean equals( Auto autoA )

{

if ( model.equals( autoA.model )

&& milesDriven == autoA.milesDriven

&& Math.abs( gallonsOfGas - autoA.gallonsOfGas ) < 0.0001 )

return true;

else

return false;

}

Page 63: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Consider

• A bank account always has methods for depositing and querying• the balance

To maintain the privacy of a client’s balance and still allow

methods in subclasses to change the balance we need to introduce

a new access modifier called protected

Page 64: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

protected

• If you create a protected data field or method it can be used within its own class or any subclass extended from it but not from the outside world

Page 65: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's
Page 66: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Example

• A standard bank account implements methods for depositing and

• querying the current balance:

public class StandardAccount extends Account {

protected double balance;

Account (){

balance = 0.0;

}

public void lodgement (double amt){

balance = balance + amt;

}

public double getBalance (){

return balance;

}

}

Page 67: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

Exercises

• 1.  True or false?  Any of the access modifiers, public, protected, or private, can be applied to a top-level class.

• 2.  Which, if any, of the following declarations are legal? • A.  public MyClass {//...} • B.  public protected int myVar; • C.  friendly Button myButton; • D.  Label myLabel

Page 68: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

• 3.  True or false?  Access  modifiers control which classes may use a feature.  A class' features are:

• The class itself.

• Its class variables.

• Its methods and constructors

Page 69: Java Sub and superclasses using extends. Subclass Constructors The following example illustrates how to use the super keyword to invoke a superclass's

• 4.  True or false?  Top-level classes that are declared private may be accessed only by other classes in the same package.