Learn advanced testing techniques and debugging strategies for Java applications.
Advanced inheritance and polymorphism concepts are crucial for designing robust, maintainable, and extensible applications. A deeper understanding of these concepts allows developers to leverage the full power of object-oriented programming.
class Parent {
public void doWork() {
System.out.println("Parent working");
this.prepareWork(); // Will call Child's implementation if called on Child
}
public void prepareWork() {
System.out.println("Parent preparing");
}
}
class Child extends Parent {
@Override
public void prepareWork() {
System.out.println("Child preparing");
}
}
// Usage
Parent p = new Child();
p.doWork(); // Outputs: "Parent working" followed by "Child preparing"
public class DatabaseConnection {
protected Connection getConnection() {
// Implementation that returns a database connection
// Available to subclasses but not to external classes
}
public void executeQuery(String sql) {
Connection conn = getConnection();
// Use connection to execute query
}
}
// Polymorphic assignment - reference type vs object type
Shape shape = new Circle(10); // Shape is reference type, Circle is object type
shape.area(); // Calls Circle's implementation
// Accessing subclass-specific methods requires casting
if (shape instanceof Circle) {
Circle circle = (Circle) shape;
double diameter = circle.getDiameter(); // Method only available in Circle
}