Class and instance initializers are blocks of code outside constructors or methods. A class can have any number of initializers. They can be anywhere in the class body and are called in the order that they appear in the source code. Class initializers (also called static initialization blocks) use the ..Continue Reading
An interface is a reference type similar to an abstract class but it can contain only: Constants. All fields defined in an interface are implicitly public, static, and final (these modifiers can and should be omitted) Abstract methods to be implemented by classes implementing the interface. Except for default methods, ..Continue Reading
Abstract classes are usually meant to share pieces of implementation and to be extended:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public abstract class Employee { protected String position; protected int experience; private String name; // non-abstract methods (same implementation for all descendant classes) public String getName() { return name; } // abstract methods (to be implemented -differently- by descendant classes) abstract void getSalary(); } |
Abstract methods are methods declared without an implementation (no body and semicolon at the end).
1 2 3 |
abstract void getSalary(); |
An important thing to remember about abstract methods is that if a class has one or more abstract methods then ..Continue Reading
In order to try and explain the important topic of polymorphism in Java, I will use the following class hierarchy as an example:
1 2 3 4 5 6 7 |
class Device { } class MobileDevice extends Device {} class DesktopDevice extends Device {} class WearableDevice extends Device {} |
Given this class hierarchy, what could we say about MobileDevice? It’s a descendant from Device (and implicitly from Object) so we could say: A MobileDevice is a ..Continue Reading
Excluding Object, which has no superclass, every Java class has one and only one direct superclass. That superclass is implicitly Object if no other superclass is specified using the reserved word extends. If class B extends from class A, then the subclass B inherits the accessible members from the superclass A. ..Continue Reading