Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sub and superclasses using extends

Similar presentations


Presentation on theme: "Sub and superclasses using extends"— Presentation transcript:

1 Sub and superclasses using extends
Java Sub and superclasses using extends

2 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

3 Class bicycle public 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

4 Methods public 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;

5 MountainBike subclass
MountainBike is a subclass of Bicycle.

6 Subclass MountainBike
public 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;

7 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.

8 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.

9 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.

10 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.

11 Super Consider this class, Superclass: public class Superclass {
public void printMethod() { System.out.println("Printed in Superclass."); } }

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

13 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

14 Class Modifiers So far we have seen many examples of such modifiers
E.g. Public Abstract etc 14

15 Terminology Access Modifier
determines access rights for the class and its members defines where the class and its members can be used 15

16 Class Modifiers A class declaration may include class modifiers.
ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final 16

17 Field Modifiers FieldModifiers: FieldModifier FieldModifiers
FieldModifier FieldModifier: one of public protected private static final 17

18 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 18

19 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 19

20 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 20

21 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 21

22 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! 22

23 Private Private if its only visible from inside the class definition
This is compromised somewhat by public access methods 23

24 Example public class Secret { private String theSecret;
private String getSecret (){ ... } Both theSecret and getSecret variables are only accessible inside the class 24

25 Consider public class NotSoSecret extends Secret { ...
public void getSecret(){ super.getSecret(); } You can’t access getSecret by inheritance because its private 25

26 mySecret.getSecret(); myDiary.getSecret();
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 26

27 Class Modifiers A class declaration may include class modifiers.
ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final 27

28 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 28

29 Examples of Instance Variable Definitions
private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height; 29

30 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. 30

31 The Auto Class public class Auto { private String model;
private int milesDriven; private double gallonsOfGas; } 31

32 Field Modifiers FieldModifiers: FieldModifier FieldModifiers
FieldModifier FieldModifier: one of public protected private static final 32

33 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 33

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

35 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. 35

36 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? Call static class methods? Call non-static instance methods? Use the object reference this? 36

37 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 37

38 Example private final int PERFECT_SCORE = 100, 38

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

40 Then the following would not be allowed:
class Programmer extends Person { ... // the body of the class } 40

41 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. 41

42 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. 42

43 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.

44 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 44

45 Value-Returning Methods
Use a return statement to return the value Syntax: return expression; 45

46 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). 46

47 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. 47

48 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 48

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

50 Accessor Methods Example: the accessor method for model. return model;
public String getModel( ) { return model; } 50

51 Mutator Methods Allow client to change the values of instance variables public void setInstanceVariable( dataType newValue ) { // validate newValue, // then assign to instance variable } 51

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

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

54 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 54

55 Using this in a Mutator Method
public 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. 55

56 The toString Method Returns a String representing the data of an object Client can call toString explicitly by coding the method call. 56

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

58 The toString API Return value Method name and argument list
returns a String representing the data of an object 58

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

60 The equals Method Determines if the data in another object is equal to the data in this object Return 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. 60

61 Example Example client code using Auto references auto1 and auto2:
if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" ); 61

62 Auto Class equals Method
public boolean equals( Auto autoA ) { if ( model.equals( autoA.model ) && milesDriven == autoA.milesDriven && Math.abs( gallonsOfGas autoA.gallonsOfGas ) < ) return true; else return false; } 62

63 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 63

64 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 64

65 65

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

67 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 67

68 Its methods and constructors
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 68

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


Download ppt "Sub and superclasses using extends"

Similar presentations


Ads by Google