Oops 3
Oops 3
What you will learn in this lecture?
Final Keyword
● When a variable is declared with a final keyword, its value can’t be modified,
essentially, a constant. This also means that you must initialize a final
variable.
● If the final variable is a reference, this means that the variable cannot be
re-bound to reference another object, but the internal state of the object
pointed by that reference variable can be changed i.e. you can add or
remove elements from the final array or final list.
Example:
1
Refer to the course videos to see the use case and more about the final keyword.
Abstract Classes
An abstract class can be considered as a blueprint for other classes. Abstract
classes are classes that contain one or more abstract methods. An abstract method
is a method that has a declaration but does not have an implementation. This set of
methods must be created within any child classes which inherit from the abstract
class. A class that contains one or more abstract methods is called an a
bstract class.
The given Java code uses the ABC class and defines an abstract base class:
2
class Test{
public static void main(String[] args) {
add x = new add(10);
mul y = new mul(10);
System.out.println(x.do_something());
System.out.println(y.do_something());
}
}
52
420
Thus, we can observe that a class that is derived from an abstract class cannot be
instantiated unless all of its abstract methods are overridden.
Note: C
oncrete classes contain only concrete (normal) methods whereas abstract
classes may contain both concrete methods and abstract methods.
3
class Test{
public static void main(String[] args) {
AnotherSubclass x = new AnotherSubclass()
x.do_something() //calling abstract method
x.do_something2() //Calling concrete method
4
}
}
We will get the output as:
Another Example
The given code shows another implementation of an abstract class.
// Driver code
5
class Test{
public static void main(String[] args) {
Animal R = new Human();
R.move();
Animal K = Snake();
K.move();
R = Dog();
R.move();
}
}
Interfaces
Writing an interface is similar to writing a class. But a class describes the attributes
and behaviors of an object. And an interface contains behaviors that a class
implements.
6
Declaring Interface
Example:
Now we need to implement this interface using a different class. A class uses the
implements keyword to implement an interface. The i mplements k
eyword appears
in the class declaration following the extends portion of the declaration.
@Override
public void print() {
// TODO Auto-generated method stub
// We can implement this function further.
}
@Override
public int getMaxSpeed() {
7
@Override
public String getCompany() {
// TODO Auto-generated method stub
return null;
}
}
@Override annotation informs the compiler that the element is meant to override
an element declared in an interface.
We can implement the given overridden functions and instantiate an object of
Vehicle class.
8