1/4
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
What is abstraction?
In Java, abstraction allows a parent class or interface to define the subclass structure (through method signatures) while leaving the actual implementation to child classes. This ensures that different objects can share a common interface without revealing the implementation details.
What are the benefits of abstraction?
Simplifies complex systems and encourages reusability.
What are abstract classes?
Contain abstract methods with no implementation. They cannot be instantiated (thus cannot have objects made from them). They essentially define the names of methods that will be inherited into subclasses, where their processes will be later defined. Abstract classes can also contain constructors and concrete methods. Abstract methods MUST be implemented by subclasses.
abstract class Animal { abstract void makeSound(); }
class Dog extends Animal { void makeSound() { System.out.println(“Woof Woof!”); } }
What are interfaces? What keyword do interfaces use?
Define a contract of behaviours that classes that implement the interface MUST follow. Since Java does not support multiple inheritance, you can do so through interfaces.
interface Animal { void makeSound(); }
class Dog implements Animal { public void makeSound() { System.out.println(“Woof Woof!”); } }
Are interfaces data types?
Yes! Interfaces are basically a way of creating your own custom data type in Java which has its own methods that every class which implements it must @Override.
Check out this example:
// This is an interface Payable.
public interface Payable {
void pay(double amount);
}
//These two concrete classes implement Payable in different ways through @Override.
public class CreditCardPayment implements Payable {
@Override
public void pay(double amount) {
System.out.println("Paid $" + amount + " using Credit Card.");
}
}
public class PayPalPayment implements Payable {
@Override
public void pay(double amount) {
System.out.println("Paid $" + amount + " using PayPal.");
}
}
// No we have Checkout class, objects of which will be created every time you want to checkout a new order. We want to use the Payable interface but Checkout will not itself implement the pay() method, so to access the pay() method we can create a variable of the interface type.
public class Checkout {
private Payable paymentMethod;
public Checkout(Payable paymentMethod) {
this.paymentMethod = paymentMethod;
}
public void processOrder(double total) {
System.out.println("Processing order...");
paymentMethod.pay(total); // Polymorphism in action!
}
}
//Therefore:
public class Main {
public static void main(String[] args) {
Payable payment1 = new CreditCardPayment();
Payable payment2 = new PayPalPayment();
Checkout order1 = new Checkout(payment1);
order1.processOrder(100.0);
Checkout order2 = new Checkout(payment2);
order2.processOrder(75.5);
}
}