COMP 213 Advanced Object-oriented Programming Lecture 5 Modifiers: - - PowerPoint PPT Presentation

comp 213
SMART_READER_LITE
LIVE PREVIEW

COMP 213 Advanced Object-oriented Programming Lecture 5 Modifiers: - - PowerPoint PPT Presentation

COMP 213 Advanced Object-oriented Programming Lecture 5 Modifiers: final and static. Access & non-access modifiers Access modifiers help you set the level of access you want for your classes, your variables and your methods, e.g.,


slide-1
SLIDE 1

COMP 213

Advanced Object-oriented Programming Lecture 5 Modifiers: final and static.

slide-2
SLIDE 2

Access & non-access modifiers

  • Access modifiers help you set the level of access you want for your classes, your

variables and your methods, e.g., private or public.

  • Java also provides a number of non-access modifiers to achieve many other

functionalities:

  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
slide-3
SLIDE 3

Access & non-access modifiers

  • Access modifiers help you set the level of access you want for your classes, your

variables and your methods, e.g., private or public.

  • Java also provides a number of non-access modifiers to achieve many other

functionalities:

  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
slide-4
SLIDE 4

Access & non-access modifiers

  • Access modifiers help you set the level of access you want for your classes, your

variables and your methods, e.g., private or public.

  • Java also provides a number of non-access modifiers to achieve many other

functionalities:

  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
slide-5
SLIDE 5

Access & non-access modifiers

  • Access modifiers help you set the level of access you want for your classes, your

variables and your methods, e.g., private or public.

  • Java also provides a number of non-access modifiers to achieve many other

functionalities:

  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
slide-6
SLIDE 6

Access & non-access modifiers

  • Access modifiers help you set the level of access you want for your classes, your

variables and your methods, e.g., private or public.

  • Java also provides a number of non-access modifiers to achieve many other

functionalities:

  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
slide-7
SLIDE 7

Access & non-access modifiers

  • Access modifiers help you set the level of access you want for your classes, your

variables and your methods, e.g., private or public.

  • Java also provides a number of non-access modifiers to achieve many other

functionalities:

  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
slide-8
SLIDE 8

The static modifier

  • static (or class) Variables:
  • The static keyword is used to create variables that will exist independently of any

instances created for the class. Only one copy of the static variable exists regardless

  • f the number of instances of the class.
  • Local variables cannot be declared static : if a variable is declared inside a method

in a class, it only has scope "within" the method, i.e., it is local.

slide-9
SLIDE 9

The static modifier

  • static (or class) Variables:
  • The static keyword is used to create variables that will exist independently of any

instances created for the class. Only one copy of the static variable exists regardless

  • f the number of instances of the class.
  • Local variables cannot be declared static : if a variable is declared inside a method

in a class, it only has scope "within" the method, i.e., it is local.

slide-10
SLIDE 10
  • static Methods
  • The static keyword is used to create methods that will exist independently of any

instances created for the class.

  • static methods do not use any instance variables of any object of the class they are

defined in.

  • static methods take all the data from parameters and compute something from those

parameters, with no reference to variables.

  • static variables & methods can be accessed using the class name followed by a dot and

the name of the variable or method.

The static modifier

slide-11
SLIDE 11
  • static Methods
  • The static keyword is used to create methods that will exist independently of any

instances created for the class.

  • static methods do not use any instance variables of any object of the class they are

defined in.

  • static methods take all the data from parameters and compute something from those

parameters, with no reference to variables.

  • static variables & methods can be accessed using the class name followed by a dot and

the name of the variable or method.

The static modifier

slide-12
SLIDE 12
  • static Methods
  • The static keyword is used to create methods that will exist independently of any

instances created for the class.

  • static methods do not use any instance variables of any object of the class they are

defined in.

  • static methods take all the data from parameters and compute something from those

parameters, with no reference to variables.

  • static variables & methods can be accessed using the class name followed by a dot and

the name of the variable or method.

The static modifier

slide-13
SLIDE 13
  • static Methods
  • The static keyword is used to create methods that will exist independently of any

instances created for the class.

  • static methods do not use any instance variables of any object of the class they are

defined in.

  • static methods take all the data from parameters and compute something from those

parameters, with no reference to variables.

  • static variables & methods can be accessed using the class name followed by a dot and

the name of the variable or method.

The static modifier

slide-14
SLIDE 14

Example 1

public class CounterOfInstances { // Stores the total number of instances created. private static int numberOfInstances = 0; // Returns the total number of instances created. static int getCounter() { return numberOfInstances; } // Increases the total number of instances created. private static void addInstance() { numberOfInstances++; } // The default constructor CounterOfInstances() { CounterOfInstances.addInstance(); } }

slide-15
SLIDE 15

Example 1

public class CounterOfInstances { // Stores the total number of instances created. private static int numberOfInstances = 0; // Returns the total number of instances created. static int getCounter() { return numberOfInstances; } // Increases the total number of instances created. private static void addInstance() { numberOfInstances++; } // The default constructor CounterOfInstances() { CounterOfInstances.addInstance(); } }

slide-16
SLIDE 16

Example 1

public class CounterOfInstances { // Stores the total number of instances created. private static int numberOfInstances = 0; // Returns the total number of instances created. static int getCounter() { return numberOfInstances; } // Increases the total number of instances created. private static void addInstance() { numberOfInstances++; } // The default constructor CounterOfInstances() { CounterOfInstances.addInstance(); } }

slide-17
SLIDE 17

Example 1

public class CounterOfInstances { // Stores the total number of instances created. private static int numberOfInstances = 0; // Returns the total number of instances created. static int getCounter() { return numberOfInstances; } // Increases the total number of instances created. private static void addInstance() { numberOfInstances++; } // The default constructor CounterOfInstances() { CounterOfInstances.addInstance(); } }

slide-18
SLIDE 18

Example 1

public static void main(String[] args) { System.out.println("At the beginning, we have " + CounterOfInstances.getCounter() + " instances of the class."); // We create 10 new instances of the class CounterOfInstances. for (int i = 0; i < 10; i++) new CounterOfInstances(); System.out.println("We have now created " + CounterOfInstances.getCounter() + " instances of the class."); }

slide-19
SLIDE 19

Example 1

public static void main(String[] args) { System.out.println("At the beginning, we have " + CounterOfInstances.getCounter() + " instances of the class."); // We create 10 new instances of the class CounterOfInstances. for (int i = 0; i < 10; i++) new CounterOfInstances(); System.out.println("We have now created " + CounterOfInstances.getCounter() + " instances of the class."); }

slide-20
SLIDE 20

Example 1

public static void main(String[] args) { System.out.println("At the beginning, we have " + CounterOfInstances.getCounter() + " instances of the class."); // We create 10 new instances of the class CounterOfInstances. for (int i = 0; i < 10; i++) new CounterOfInstances(); System.out.println("We have now created " + CounterOfInstances.getCounter() + " instances of the class."); }

slide-21
SLIDE 21

Example 2

public class Car { private String colour; private int year; private int speed; // add an instance variable for the object ID. private int id; // add a class variable for the number of Car // objects instantiated. private static int numberOfCars = 0;

...

}

slide-22
SLIDE 22

Example 2

public class Car { private String colour; private int year; private int speed; // add an instance variable for the object ID. private int id; // add a class variable for the number of Car // objects instantiated. private static int numberOfCars = 0;

...

}

slide-23
SLIDE 23

Example 2

public class Car { private String colour; private int year; private int speed; // add an instance variable for the object ID. private int id; // add a class variable for the number of Car // objects instantiated. private static int numberOfCars = 0;

...

}

slide-24
SLIDE 24

Example 2

public class Car { private String colour; private int year; private int speed; // add an instance variable for the object ID. private int id; // add a class variable for the number of Car // objects instantiated. private static int numberOfCars = 0;

...

}

slide-25
SLIDE 25

Example 2

public class Car { private String colour; private int year; private int speed; // add an instance variable for the object ID. private int id; // add a class variable for the number of Car // objects instantiated. private static int numberOfCars = 0;

...

}

slide-26
SLIDE 26

Example 2

public class Car { private String colour; private int year; private int speed; // add an instance variable for the object ID. private int id; // add a class variable for the number of Car // objects instantiated. private static int numberOfCars = 0;

...

}

slide-27
SLIDE 27

Example 2

public class Car { ... // Constructor public Car(String carColour, int maxSpeed, int startYear) { year = startYear; colour = carColour; speed = maxSpeed; // increment number of Cars // and assign ID number id = ++numberOfCars; }

...

}

slide-28
SLIDE 28

Example 2

public class Car { ... // Constructor public Car(String carColour, int maxSpeed, int startYear) { year = startYear; colour = carColour; speed = maxSpeed; // increment number of Cars // and assign ID number id = ++numberOfCars; }

...

}

slide-29
SLIDE 29

Example 2

public class Car { ... // Constructor public Car(String carColour, int maxSpeed, int startYear) { year = startYear; colour = carColour; speed = maxSpeed; // increment number of Cars // and assign ID number id = ++numberOfCars; }

...

}

slide-30
SLIDE 30

Example 2

public class Car { ... // Constructor public Car(String carColour, int maxSpeed, int startYear) { year = startYear; colour = carColour; speed = maxSpeed; // increment number of Cars // and assign ID number id = ++numberOfCars; }

...

}

slide-31
SLIDE 31

Example 2

public class Car { ... // Constructor public Car(String carColour, int maxSpeed, int startYear) { year = startYear; colour = carColour; speed = maxSpeed; // increment number of Cars // and assign ID number id = ++numberOfCars; }

...

}

You can use the Car constructor to set the id instance variable and increment the numberOfCars class variable.

slide-32
SLIDE 32

Example 2

public class Car { ... // new method (getter) to return the ID instance variable public int getID() { return id; } // method to return total number of Cars public static int getNumberOfCars() { return numberOfCars; } ... }

slide-33
SLIDE 33

Example 2

public class Car { ... // new method (getter) to return the ID instance variable public int getID() { return id; } // method to return total number of Cars public static int getNumberOfCars() { return numberOfCars; } ... }

slide-34
SLIDE 34

Example 2

public class Car { ... // new method (getter) to return the ID instance variable public int getID() { return id; } // method to return total number of Cars public static int getNumberOfCars() { return numberOfCars; } ... }

slide-35
SLIDE 35

Example 2

public class Car { ... // getter method for Car’s year public int getYear() { return year; } ... }

slide-36
SLIDE 36

Example 2

public class Car { ... // getter method for Car’s year public int getYear() { return year; } ... }

slide-37
SLIDE 37

Example 2

public class Car { ... // getter method for Car’s colour public String getColour() { return colour; } // setter method for Car’s colour public void setColour(String newVal) { this.colour = newVal; } ... }

slide-38
SLIDE 38

Example 2

public class Car { ... // getter method for Car’s colour public String getColour() { return colour; } // setter method for Car’s colour public void setColour(String newVal) { this.colour = newVal; } ... }

slide-39
SLIDE 39

Example 2

public class Car { ... // getter method for Car’s colour public String getColour() { return colour; } // setter method for Car’s colour public void setColour(String newVal) { this.colour = newVal; } ... }

slide-40
SLIDE 40

Example 2

public class Car { ... // getter method for Car’s speed public int getSpeed() { return speed; } // method for increasing Car’s speed public void speedUp(int increment) { this.speed += increment; } // method for decreasing Car’s speed public void speedDown(int decrement) { this.speed -= decrement; } ... }

slide-41
SLIDE 41

Example 2

public class Car { ... // getter method for Car’s speed public int getSpeed() { return speed; } // method for increasing Car’s speed public void speedUp(int increment) { this.speed += increment; } // method for decreasing Car’s speed public void speedDown(int decrement) { this.speed -= decrement; } ... }

slide-42
SLIDE 42

Example 2

public class Car { ... // getter method for Car’s speed public int getSpeed() { return speed; } // method for increasing Car’s speed public void speedUp(int increment) { this.speed += increment; } // method for decreasing Car’s speed public void speedDown(int decrement) { this.speed -= decrement; } ... }

slide-43
SLIDE 43

Example 2

public class Car { ... // getter method for Car’s speed public int getSpeed() { return speed; } // method for increasing Car’s speed public void speedUp(int increment) { this.speed += increment; } // method for decreasing Car’s speed public void speedDown(int decrement) { this.speed -= decrement; } ... }

slide-44
SLIDE 44

Example 2

public class Car { ... // Main method public static void main(String[] args) { Car audiCar = new Car("red", 100, 2010); System.out.println(Car.numberOfCars); System.out.println(audiCar.id); audiCar.getNumberOfCars(); // warning! System.out.println(audiCar.numberOfCars); // warning! } }

slide-45
SLIDE 45

Example 2

public class Car { ... // Main method public static void main(String[] args) { Car audiCar = new Car("red", 100, 2010); System.out.println(Car.numberOfCars); System.out.println(audiCar.id); audiCar.getNumberOfCars(); // warning! System.out.println(audiCar.numberOfCars); // warning! } }

slide-46
SLIDE 46

Example 2

public class Car { ... // Main method public static void main(String[] args) { Car audiCar = new Car("red", 100, 2010); System.out.println(Car.numberOfCars); System.out.println(audiCar.id); audiCar.getNumberOfCars(); // warning! System.out.println(audiCar.numberOfCars); // warning! } }

slide-47
SLIDE 47

Example 2

public class Car { ... // Main method public static void main(String[] args) { Car audiCar = new Car("red", 100, 2010); System.out.println(Car.numberOfCars); System.out.println(audiCar.id); audiCar.getNumberOfCars(); // warning! System.out.println(audiCar.numberOfCars); // warning! } }

slide-48
SLIDE 48

Example 2

public class Car { ... // Main method public static void main(String[] args) { Car audiCar = new Car("red", 100, 2010); System.out.println(Car.numberOfCars); System.out.println(audiCar.id); audiCar.getNumberOfCars(); // warning! System.out.println(audiCar.numberOfCars); // warning! } }

You can also refer to static methods with an object reference; discouraged because it does not make it clear that they are class methods.

slide-49
SLIDE 49

Example 2

public class Car { ... // Main method public static void main(String[] args) { Car audiCar = new Car("red", 100, 2010); System.out.println(Car.numberOfCars); System.out.println(audiCar.id); audiCar.getNumberOfCars(); // warning! System.out.println(audiCar.numberOfCars); // warning! } }

You can also refer to static fields with an object reference; discouraged because it does not make it clear that they are class variables.

slide-50
SLIDE 50

Notice

  • Not all combinations of instance and class variables & methods are allowed:
  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they

must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

slide-51
SLIDE 51

The final modifier

  • finalVariables:
  • A final variable can be explicitly initialized only once. A reference variable declared

final can never be reassigned to refer to an different object.

  • With variables, the final modifier often is used together with static to make the

constant a class variable.

slide-52
SLIDE 52

The final modifier

  • finalVariables:
  • A final variable can be explicitly initialized only once. A reference variable declared

final can never be reassigned to refer to an different object.

  • With variables, the final modifier often is used together with static to make the

constant a class variable.

slide-53
SLIDE 53

Example

  • Constants defined in this way cannot be reassigned; you get a compile-time

error if your program tries to do so.

  • By convention, the names of constant values are spelled in uppercase
  • letters. If the name is composed of more than one word, the words are

separated by an underscore (_).

static final double PI = 3.141592653589793;

slide-54
SLIDE 54

The final modifier

  • final Methods:
  • A final method cannot be overridden/modified by any subclasses.
  • The main purpose of making a method final would be to prevent outsiders changing

the content of the method.

  • Note: Methods called from constructors should generally be declared final. If a

constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.

slide-55
SLIDE 55

Example

class ChessPlaying { final String getFirstPlayer() { return "WHITE"; } } class MyChessRules extends ChessPlaying { @Override public final String getFirstPlayer() { return "BLACK"; // compilation error: overridden method is final } }

slide-56
SLIDE 56

Example

class ChessPlaying { final String getFirstPlayer() { return "WHITE"; } } class MyChessRules extends ChessPlaying { @Override public final String getFirstPlayer() { return "BLACK"; // compilation error: overridden method is final } }

slide-57
SLIDE 57

Example

class ChessPlaying { final String getFirstPlayer() { return "WHITE"; } } class MyChessRules extends ChessPlaying { @Override public final String getFirstPlayer() { return "BLACK"; // compilation error: overridden method is final } }

slide-58
SLIDE 58

The final modifier

  • final Methods:
  • A final method cannot be overridden/modified by any subclasses.
  • The main purpose of making a method final would be to prevent outsiders changing

the content of the method.

  • Note: Methods called from constructors should generally be declared final. If a

constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.

slide-59
SLIDE 59

The final modifier

  • final Classes:
  • The main purpose of declaring a class final is to prevent it from being subclassed.
  • If a class is marked as final, then no class can inherit any feature from it.
slide-60
SLIDE 60

Example

class Point1d { int x; } class Point2d extends Point1d { int y; } final class Point3d extends Point2d { int z; } class FinalClassExample { public static void main(String args[]) { Point3d obj = new Point3d();

  • bj.z = 10;
  • bj.y = 1;
  • bj.x = 5;

System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z); } }

slide-61
SLIDE 61

Example

class Point1d { int x; } class Point2d extends Point1d { int y; } final class Point3d extends Point2d { int z; } class FinalClassExample { public static void main(String args[]) { Point3d obj = new Point3d();

  • bj.z = 10;
  • bj.y = 1;
  • bj.x = 5;

System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z); } }

slide-62
SLIDE 62

Example

class Point1d { int x; } class Point2d extends Point1d { int y; } final class Point3d extends Point2d { int z; } class FinalClassExample { public static void main(String args[]) { Point3d obj = new Point3d();

  • bj.z = 10;
  • bj.y = 1;
  • bj.x = 5;

System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z); } }

slide-63
SLIDE 63

Example

class Point1d { int x; } class Point2d extends Point1d { int y; } final class Point3d extends Point2d { int z; } class FinalClassExample { public static void main(String args[]) { Point3d obj = new Point3d();

  • bj.z = 10;
  • bj.y = 1;
  • bj.x = 5;

System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z); } }

We would get a compile- time error if we tried to extend this class further.

slide-64
SLIDE 64

The abstract modifier

  • abstract Classes:
  • An abstract class can never be instantiated. If a class is declared as abstract then

its sole purpose is to be extended.

  • If a class contains abstract methods then the class should be declared abstract.

Otherwise, a compile error will be thrown.

  • An abstract class may contain both abstract methods as well “normal” methods.
slide-65
SLIDE 65

The abstract modifier

  • abstract Methods:
  • An abstract method is a method declared without any implementation. The

method’s body (implementation) is provided by the subclass.

  • Any class that extends an abstract class must implement all the abstract

methods of the super class, unless the subclass is also an abstract class.

  • If a class contains one or more abstract methods, then the class must be declared
  • abstract. An abstract class does not need to contain abstract methods.
  • An abstract method ends with a semicolon, e.g: public abstract run();

Can abstract methods be final?

slide-66
SLIDE 66

Example 1

public abstract class SuperClass { abstract void m(); // abstract method } class SubClass extends SuperClass { void m() { ... // must implement the abstract method! } }

slide-67
SLIDE 67

Example 1

public abstract class SuperClass { abstract void m(); // abstract method } class SubClass extends SuperClass { void m() { ... // must implement the abstract method! } }

slide-68
SLIDE 68

Example 2

public abstract class Van { private String name; Van(String vanName){ name = vanName; } public abstract void goFast(); // an abstract method public abstract void changeColor(); // another abstract method public void start() { System.out.println("Van " + name + " started"); } }

slide-69
SLIDE 69

Example 2

public abstract class Van { private String name; Van(String vanName){ name = vanName; } public abstract void goFast(); // an abstract method public abstract void changeColor(); // another abstract method public void start() { System.out.println("Van " + name + " started"); } }

slide-70
SLIDE 70

Example 2

public abstract class Van { private String name; Van(String vanName){ name = vanName; } public abstract void goFast(); // an abstract method public abstract void changeColor(); // another abstract method public void start() { System.out.println("Van " + name + " started"); } }

slide-71
SLIDE 71

Example 2

public abstract class Van { private String name; Van(String vanName){ name = vanName; } public abstract void goFast(); // an abstract method public abstract void changeColor(); // another abstract method public void start() { System.out.println("Van " + name + " started"); } }

slide-72
SLIDE 72

Example 2

public class Caravan extends Van { Caravan(String vanName) { super(vanName); } public void goFast() { System.out.println("Caravan going fast!"); } public void changeColor() { ... } public static void main(String[] args) { Caravan c1 = new Caravan("Fury"); c1.start(); } }

slide-73
SLIDE 73

Example 2

public class Caravan extends Van { Caravan(String vanName) { super(vanName); } public void goFast() { System.out.println("Caravan going fast!"); } public void changeColor() { ... } public static void main(String[] args) { Caravan c1 = new Caravan("Fury"); c1.start(); } }

slide-74
SLIDE 74

Example 2

public class Caravan extends Van { Caravan(String vanName) { super(vanName); } public void goFast() { System.out.println("Caravan going fast!"); } public void changeColor() { ... } public static void main(String[] args) { Caravan c1 = new Caravan("Fury"); c1.start(); } }

slide-75
SLIDE 75

Example 2

public class Caravan extends Van { Caravan(String vanName) { super(vanName); } public void goFast() { System.out.println("Caravan going fast!"); } public void changeColor() { ... } public static void main(String[] args) { Caravan c1 = new Caravan("Fury"); c1.start(); } }

slide-76
SLIDE 76

Example 2

public class Caravan extends Van { Caravan(String vanName) { super(vanName); } public void goFast() { System.out.println("Caravan going fast!"); } public void changeColor() { ... } public static void main(String[] args) { Caravan c1 = new Caravan("Fury"); c1.start(); } }

slide-77
SLIDE 77

Question

  • Can a class be declared both abstract and final?
slide-78
SLIDE 78

Answer

  • A class cannot be both abstract and final
  • Reason: a final class cannot be extended and an abstract class is only meant to be

extended.

slide-79
SLIDE 79

Answer

  • A class cannot be both abstract and final
  • Reason: a final class cannot be extended and an abstract class is only meant to be

extended.

slide-80
SLIDE 80

Example

public final abstract class ErrorAbstractFinal { abstract void run(); } public class Eleni { public static void main(String[] args) { ErrorAbstractFinal err1 = new ErrorAbstractFinal(); } } Exception in thread "main" java.lang.Error: Unresolved compilation problem: The class ErrorAbstractFinal can be either abstract or final, not both

Compiler output:

slide-81
SLIDE 81

Summary

  • Non-access modifiers: final, static, abstract
  • Next: More about modifiers – scope.