Polymorphism
/**
* In Java polymorphism is the ability of an object to take many forms.
* You can access a subtype method from a super type object,
* but you must cast the object with subtype.
*/
package com.minte9.oop.polymorphism;
public class Polymorphism {
public static void main(String[] args) {
User user = new Client(); // reference is User type
user.setName("John");
// superclass method call
System.out.println(user.reading()); // John is reading
// subclass method call
System.out.println( ((Client) user).buying() ); // John is buying
}
}
// Abstract superclass
abstract class User {
protected String name;
abstract void setName(String s);
public String reading() {
return name + " is reading.";
}
}
// Subclass
class Client extends User {
public void setName(String s) {
name = s;
}
public String buying() {
return name + " is buying.";
}
}
Dependency Injection
/**
* Polymorphism and Dependency Injection
*
* FileOpener receives an Item through its constructor
* insteed of creating it itself (DI).
*
* The same method call (open) behaves differently depending
* on the concreate type (Csv or XML) provided at runtime (PO).
*/
package com.minte9.oop.polymorphism;
public class DependencyInjection {
public static void main(String[] args) {
Item csv = new Csv();
Item xml = new Xml();
FileOpener csvOpener = new FileOpener(csv);
FileOpener xmlOpener = new FileOpener(xml);
csvOpener.open(); // CSV opened
xmlOpener.open(); // XML opened
}
}
abstract class Item {
public abstract void open();
}
class Csv extends Item {
@Override
public void open() {
System.out.println("CSV opened");
}
}
class Xml extends Item {
@Override
public void open() {
System.out.println("XML opened");
}
}
class FileOpener {
private final Item item; // dependency
// Dependency Injection via constructor
public FileOpener(Item item) {
this.item = item;
}
public void open() {
item.open();
}
}
Questions and answers:
Clink on Option to Answer
1. What does polymorphism mean in Java?
- a) An object can take many forms
- b) An object can have only one type
2. In this line: User user = new Client(); — what is true?
- a) The reference type is User, but the object is Client
- b) The reference and the object are both User
3. Why is casting needed in ((Client) user).buying()?
- a) To access a child-class-only method
- b) To access a parent-class method
4. What is Dependency Injection in the example?
- a) The object is created inside FileOpener
- b) The object is provided from outside FileOpener
5. Why do Csv and Xml behave differently when open() is called?
- a) Because of polymorphism at runtime
- b) Because of method overloading