COMP 213 Advanced Object-oriented Programming Lecture 5 Modifiers: final and static.
COMP 213Advanced 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., private or public.
• Java also provides a number of non-access modifiers to achieve many other functionalities:
• The staticmodifier for creating class methods and variables.
• The finalmodifier for finalizing the implementations of classes, methods, and variables.
• The abstractmodifier for creating abstract classes and methods.
• The synchronized and volatilemodifiers, which are used for threads.
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 staticmodifier for creating class methods and variables.
• The finalmodifier for finalizing the implementations of classes, methods, and variables.
• The abstractmodifier for creating abstract classes and methods.
• The synchronized and volatilemodifiers, which are used for threads.
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 staticmodifier for creating class methods and variables.
• The finalmodifier for finalizing the implementations of classes, methods, and variables.
• The abstractmodifier for creating abstract classes and methods.
• The synchronized and volatilemodifiers, which are used for threads.
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 staticmodifier for creating class methods and variables.
• The finalmodifier for finalizing the implementations of classes, methods, and variables.
• The abstractmodifier for creating abstract classes and methods.
• The synchronized and volatilemodifiers, which are used for threads.
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 staticmodifier for creating class methods and variables.
• The finalmodifier for finalizing the implementations of classes, methods, and variables.
• The abstractmodifier for creating abstract classes and methods.
• The synchronized and volatilemodifiers, which are used for threads.
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 staticmodifier for creating class methods and variables.
• The finalmodifier for finalizing the implementations of classes, methods, and variables.
• The abstractmodifier for creating abstract classes and methods.
• The synchronized and volatilemodifiers, which are used for threads.
The staticmodifier
• 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 of 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.
The staticmodifier
• 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 of 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.
• static Methods
• The static keyword is used to create methods that will exist independently of any instances created for the class.
• staticmethods do not use any instance variables of any object of the class they are defined in.
• staticmethods 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 staticmodifier
• static Methods
• The static keyword is used to create methods that will exist independently of any instances created for the class.
• staticmethods do not use any instance variables of any object of the class they are defined in.
• staticmethods 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 staticmodifier
• static Methods
• The static keyword is used to create methods that will exist independently of any instances created for the class.
• staticmethods do not use any instance variables of any object of the class they are defined in.
• staticmethods 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 staticmodifier
• static Methods
• The static keyword is used to create methods that will exist independently of any instances created for the class.
• staticmethods do not use any instance variables of any object of the class they are defined in.
• staticmethods 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 staticmodifier
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 constructorCounterOfInstances() {
CounterOfInstances.addInstance();}
}
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 constructorCounterOfInstances() {
CounterOfInstances.addInstance();}
}
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 constructorCounterOfInstances() {
CounterOfInstances.addInstance();}
}
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 constructorCounterOfInstances() {
CounterOfInstances.addInstance();}
}
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.");
}
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.");
}
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.");
}
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;
...
}
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;
...
}
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;
...
}
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;
...
}
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;
...
}
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;
...
}
Example 2
public class Car {...// Constructorpublic Car(String carColour, int maxSpeed, int startYear) {year = startYear;colour = carColour;speed = maxSpeed;// increment number of Cars// and assign ID numberid = ++numberOfCars;}
...
}
Example 2
public class Car {...// Constructorpublic Car(String carColour, int maxSpeed, int startYear) {year = startYear;colour = carColour;speed = maxSpeed;// increment number of Cars// and assign ID numberid = ++numberOfCars;}
...
}
Example 2
public class Car {...// Constructorpublic Car(String carColour, int maxSpeed, int startYear) {year = startYear;colour = carColour;speed = maxSpeed;// increment number of Cars// and assign ID numberid = ++numberOfCars;}
...
}
Example 2
public class Car {...// Constructorpublic Car(String carColour, int maxSpeed, int startYear) {year = startYear;colour = carColour;speed = maxSpeed;// increment number of Cars// and assign ID numberid = ++numberOfCars;}
...
}
Example 2
public class Car {...// Constructorpublic Car(String carColour, int maxSpeed, int startYear) {year = startYear;colour = carColour;speed = maxSpeed;// increment number of Cars// and assign ID numberid = ++numberOfCars;}
...
}You can use the Car
constructor to set the id instance variable and
increment the numberOfCarsclass variable.
Example 2
public class Car {...// new method (getter) to return the ID instance variablepublic int getID() {return id;}// method to return total number of Carspublic static int getNumberOfCars() {return numberOfCars;}...
}
Example 2
public class Car {...// new method (getter) to return the ID instance variablepublic int getID() {return id;}// method to return total number of Carspublic static int getNumberOfCars() {return numberOfCars;}...
}
Example 2
public class Car {...// new method (getter) to return the ID instance variablepublic int getID() {return id;}// method to return total number of Carspublic static int getNumberOfCars() {return numberOfCars;}...
}
Example 2
public class Car {...// getter method for Car’s yearpublic int getYear() {return year;}...
}
Example 2
public class Car {...// getter method for Car’s yearpublic int getYear() {return year;}...
}
Example 2
public class Car {...// getter method for Car’s colourpublic String getColour() {return colour;}// setter method for Car’s colourpublic void setColour(String newVal) {this.colour = newVal;}...
}
Example 2
public class Car {...// getter method for Car’s colourpublic String getColour() {return colour;}// setter method for Car’s colourpublic void setColour(String newVal) {this.colour = newVal;}...
}
Example 2
public class Car {...// getter method for Car’s colourpublic String getColour() {return colour;}// setter method for Car’s colourpublic void setColour(String newVal) {this.colour = newVal;}...
}
Example 2
public class Car {...// getter method for Car’s speedpublic int getSpeed() {return speed;}// method for increasing Car’s speedpublic void speedUp(int increment) {this.speed += increment;}// method for decreasing Car’s speedpublic void speedDown(int decrement) {this.speed -= decrement;}...
}
Example 2
public class Car {...// getter method for Car’s speedpublic int getSpeed() {return speed;}// method for increasing Car’s speedpublic void speedUp(int increment) {this.speed += increment;}// method for decreasing Car’s speedpublic void speedDown(int decrement) {this.speed -= decrement;}...
}
Example 2
public class Car {...// getter method for Car’s speedpublic int getSpeed() {return speed;}// method for increasing Car’s speedpublic void speedUp(int increment) {this.speed += increment;}// method for decreasing Car’s speedpublic void speedDown(int decrement) {this.speed -= decrement;}...
}
Example 2
public class Car {...// getter method for Car’s speedpublic int getSpeed() {return speed;}// method for increasing Car’s speedpublic void speedUp(int increment) {this.speed += increment;}// method for decreasing Car’s speedpublic void speedDown(int decrement) {this.speed -= decrement;}...
}
Example 2
public class Car {...// Main methodpublic 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!
}}
Example 2
public class Car {...// Main methodpublic 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!
}}
Example 2
public class Car {...// Main methodpublic 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!
}}
Example 2
public class Car {...// Main methodpublic 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!
}}
Example 2
public class Car {...// Main methodpublic 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.
Example 2
public class Car {...// Main methodpublic 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.
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.
The finalmodifier
• 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 finalmodifier often is used together with static to make the constant a class variable.
The finalmodifier
• 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 finalmodifier often is used together with static to make the constant a class variable.
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 uppercaseletters. If the name is composed of more than one word, the words are separated by an underscore (_).
static final double PI = 3.141592653589793;
The finalmodifier
• finalMethods:
• A finalmethod cannot be overridden/modified by any subclasses.
• The main purpose of making a method finalwould 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.
Example
class ChessPlaying {final String getFirstPlayer() {
return "WHITE";}
}
class MyChessRules extends ChessPlaying {@Overridepublic final String getFirstPlayer() {return "BLACK"; // compilation error: overridden method is final}
}
Example
class ChessPlaying {final String getFirstPlayer() {
return "WHITE";}
}
class MyChessRules extends ChessPlaying {@Overridepublic final String getFirstPlayer() {return "BLACK"; // compilation error: overridden method is final}
}
Example
class ChessPlaying {final String getFirstPlayer() {
return "WHITE";}
}
class MyChessRules extends ChessPlaying {@Overridepublic final String getFirstPlayer() {return "BLACK"; // compilation error: overridden method is final}
}
The finalmodifier
• finalMethods:
• A finalmethod cannot be overridden/modified by any subclasses.
• The main purpose of making a method finalwould 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.
The finalmodifier
• finalClasses:
• 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.
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();obj.z = 10;obj.y = 1;obj.x = 5;System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z);
}}
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();obj.z = 10;obj.y = 1;obj.x = 5;System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z);
}}
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();obj.z = 10;obj.y = 1;obj.x = 5;System.out.println("x = " + obj.x + "\ny = " + obj.y + "\nz = " + obj.z);
}}
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();obj.z = 10;obj.y = 1;obj.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.
The abstractmodifier
• abstractClasses:
• 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 abstractmethods 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.
The abstractmodifier
• abstractMethods:
• An abstractmethod 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 abstractmethods of the super class, unless the subclass is also an abstract class.
• If a class contains one or more abstractmethods, then the class must be declared abstract. An abstract class does not need to contain abstract methods.
• An abstractmethod ends with a semicolon, e.g: public abstract run();
Can abstractmethods be final?
Example 1
public abstract class SuperClass {abstract void m(); // abstract method
}
class SubClass extends SuperClass {void m() {
... // must implement the abstract method!}
}
Example 1
public abstract class SuperClass {abstract void m(); // abstract method
}
class SubClass extends SuperClass {void m() {
... // must implement the abstract method!}
}
Example 2
public abstract class Van {
private String name;
Van(String vanName){name = vanName;
}public abstract void goFast(); // an abstract methodpublic abstract void changeColor(); // another abstract methodpublic void start() {
System.out.println("Van " + name + " started");}
}
Example 2
public abstract class Van {
private String name;
Van(String vanName){name = vanName;
}public abstract void goFast(); // an abstract methodpublic abstract void changeColor(); // another abstract methodpublic void start() {
System.out.println("Van " + name + " started");}
}
Example 2
public abstract class Van {
private String name;
Van(String vanName){name = vanName;
}public abstract void goFast(); // an abstract methodpublic abstract void changeColor(); // another abstract methodpublic void start() {
System.out.println("Van " + name + " started");}
}
Example 2
public abstract class Van {
private String name;
Van(String vanName){name = vanName;
}public abstract void goFast(); // an abstract methodpublic abstract void changeColor(); // another abstract methodpublic void start() {
System.out.println("Van " + name + " started");}
}
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();
}}
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();
}}
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();
}}
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();
}}
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();
}}
Question
• Can a class be declared both abstract and final?
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.
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.
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:
Summary
• Non-access modifiers: final, static, abstract
• Next: More about modifiers – scope.