Creating Abstract Classes
test
INTRODUCING ABSTRACT CLASSES
abstract class is a class that cannot be instantiated and may contain abstract methods.abstract method is a method that does not define an implementation when it is declared.abstract class Bird {
public abstract String getName();
public void printName() {
System.out.print(getName());
}
}
public class Stork extends Bird {
public String getName() { return "Stork!"; }
public static void main(String[] args) {
new Stork().printName();
}
}In particular, the Stork class must now override the abstract getName() method.
For example, the following implementation does not compile because Stork does not override the required abstract getName() method:
public class Stork extends Bird {} // DOES NOT COMPILE
An abstract class is most commonly used when you want another class to inherit properties of a particular class, but you want the subclass to fill in some of the implementation details.
OVERRIDE VS. IMPLEMENT
An abstract class can be initialized, but only as part of the instantiation of a nonabstract subclass.
DEFINING ABSTRACT METHODS
public abstract class Llama {
public void chew() {}
}public class Egret { // DOES NOT COMPILE
public abstract void peck();
}abstract public class Tiger {
abstract public int claw();
}public class abstract Jackal { // DOES NOT COMPILE
public int abstract howl(); // DOES NOT COMPILE
}> [!NOTE]
It is not possible to define an abstract method that has a body, or default implementation.
You can still define a method with a body—you just can’t mark it as abstract.
As long as you do not mark the method as final, the subclass has the option to override an inherited method.
cannot define body or default implementation for abstract method
Constructors in Abstract Classes
Even though abstract classes cannot be instantiated, they are still initialized through constructors by their subclasses. For example, does the following program compile?
abstract class Bear {
abstract CharSequence chew();
public Bear() {
System.out.println(chew()); // Does this compile?
}
}
public class Panda extends Bear {
String chew() { return "yummy!"; }
public static void main(String[] args) {
new Panda();
}
}Using the constructor rules you learned in Chapter 8, the compiler inserts a default no-argument constructor into the Panda class, which first calls super() in the Bear class. The Bear constructor is only called when the abstract class is being initialized through a subclass; therefore, there is an implementation of chew() at the time the constructor is called. This code compiles and prints yummy! at runtime.
For the exam, remember that abstract classes are initialized with constructors in the same way as nonabstract classes. For example, if an abstract class does not provide a constructor, the compiler will automatically insert a default no-argument constructor.
The primary difference between a constructor in an abstract class and a nonabstract class is that a constructor in abstract class can be called only when it is being initialized by a nonabstract subclass. This makes sense, as abstract classes cannot be instantiated.
Invalid Abstract Method Declarations
public abstract class Turtle {
public abstract long eat() // DOES NOT COMPILE
public abstract void swim() {}; // DOES NOT COMPILE
public abstract int getAge() { // DOES NOT COMPILE
return 10;
}
public void sleep; // DOES NOT COMPILE
public void goInShell(); // DOES NOT COMPILE
}eat(), does not compile because it is marked abstract but does not end with as semicolon (;).swim() and getAge(), do not compile because they are marked abstract, but they provide an implementation block enclosed in braces ({}).sleep, does not compile because it is missing parentheses, (), for method arguments.goInShell(), does not compile because it is not marked abstract and therefore must provide a body enclosed in braces.abstract method declaration must end in a semicolon without any braces.Invalid Modifiers
In this section, we review the abstract modifier and which modifiers it is not compatible with.
abstract and final Modifiers
abstract, you are intending for someone else to extend or implement it.final, you are preventing anyone from extending or implementing it.Due to this incompatibility, Java does not permit a class or method to be marked both abstract and final. For example, the following code snippet will not compile:
public abstract final class Tortoise { // DOES NOT COMPILE
public abstract final void walk(); // DOES NOT COMPILE
}The exam doesn’t tend to use final modifiers on classes or methods often, so if you see them, make sure they aren’t used with the abstract modifier.
abstract and private Modifiers
abstract and private.public abstract class Whale {
private abstract void sing(); // DOES NOT COMPILE
}
public class HumpbackWhale extends Whale {
private void sing() {
System.out.println("Humpback whale is singing");
}
}If we changed the access modifier from private to protected in the parent class Whale, would the code compile? Let’s take a look:
public abstract class Whale {
protected abstract void sing();
}
public class HumpbackWhale extends Whale {
private void sing() { // DOES NOT COMPILE
System.out.println("Humpback whale is singing");
}
}In this modified example, the code will still not compile, but for a completely different reason. If you remember the rules for overriding a method, the subclass cannot reduce the visibility of the parent method, sing(). Because the method is declared protected in the parent class, it must be marked as protected or public in the child class. Even with abstract methods, the rules for overriding methods must be followed.
test
> [!NOTE]
While it is not possible to declare a method abstract and private,
it is possible (albeit redundant) to declare a method final and private.
test
abstract and static Modifiers
abstract class Hippopotamus {
abstract static void swim(); // DOES NOT COMPILE
}For the exam, make sure you know which modifiers can and cannot be used with one another, especially for abstract classes and interfaces.
CREATING A CONCRETE CLASS
abstract class becomes usable when it is extended by a concrete subclass.abstract class is required to implement all inherited abstract methods.REVIEWING ABSTRACT CLASS RULES
Abstract Class Definition Rules
1. Abstract classes cannot be instantiated.
2. All top-level types, including abstract classes, cannot be marked protected or private.
3. Abstract classes cannot be marked final.
4. Abstract classes may include zero or more abstract and nonabstract methods.
5. An abstract class that extends another abstract class inherits all of its abstract methods.
6. The first concrete class that extends an abstract class must provide an implementation for all of the inherited abstract methods.
7. Abstract class constructors follow the same rules for initialization as regular constructors, except they can be called only as part of the initialization of a subclass.
Abstract Method Definition Rules
Abstract Method Definition Rules
1. Abstract methods can be defined only in abstract classes or interfaces.
2. Abstract methods cannot be declared private or final.
3. Abstract methods must not provide a method body/implementation in the abstract class in which they are declared.
4. Implementing an abstract method in a subclass follows the same rules for overriding a method, including covariant return types, exception declarations, etc.
Implementing Interfaces
interfaces.interface is an abstract data type are that declares a list of abstract methods that any class implementing the interface must provide.interface can also include constant variables.abstract methods and constant variables included with an interface are implicitly assumed to be public.INTERFACES AND NONABSTRACT METHODS
interfaces: abstract methods and constant variables.interfaces were updated to include static and default methods.default method is one in which the interface method has a body and is not marked abstract.private and private static methods.DEFINING AN INTERFACE
public abstract interface CanBurrow {
public abstract Float getSpeed(int age);
public static final int MINIMUM_DEPTH = 2;public or default (package-private) access modifierabstract)interface keywordpublic abstract) - Abstract interface methodpublic static final) - Interface variableOne aspect of an interface declaration that differs from an abstract class is that it contains implicit modifiers. An implicit modifier is a modifier that the compiler automatically adds to a class, interface, method, or variable declaration.
public abstract interface WalksOnTwoLegs {}public class Biped {
public static void main(String[] args) {
var e = new WalksOnTwoLegs(); // DOES NOT COMPILE
}
}
public final interface WalksOnEightLegs {} // DOES NOT COMPILEWalksOnTwoLegs is an interface and cannot be instantiated.final for the same reason that abstract classes cannot be marked as final. In other words, marking an interface final implies no class could ever implement it.How do you use an interface?
test
Implementing an interface
public class FieldMouse implements Climb, CanBurrow {
public Float getSpeed(int age) {
return 11f;
}
}Many of the rules for class declarations also apply to interfaces including the following :
top-level class or interface can only be declared with public or package-private access.It may help to think of an interface as a specialized abstract class, as many of the rules carry over. Just remember that an interface does not follow the same rules for single inheritance and instance initialization with constructors, as a class does.
test