Polymorphism

Publish date: 2024-06-24
Tags: System-Design, Software-Engineering

Polymorphism

Subtyping

public class User {
	private String name;
	private String email;
}

public class Student extends User {
	private String batchName;
	private Integer psp;
}

User user = new Student();

Method Overloading (Compile time polymorphism)

public class User {
	private String name;
	private String email;
	
	public void printUser() {
		System.out.println("Name: " + name + ", Email: " + email);
	}
	
	public void printUser(String name, String email) {
		System.out.println("Name: " + name + ", Email: " + email);
	}
}

Method Overriding (Runtime polymorphism)

public class User {
	private String name;
	private String email;

	public void printUser() {
		System.out.println("Name: " + name + ", Email: " + email);
	}
}

public class Student extends User {
	private String batchName;
	private Integer psp;

	@Override
	public void printUser() {
		System.out.println("Name: " + name + ", Email: " + email + ",
		Batch: " + batchName + ", PSP: " + psp);
	}
}

Advantages of Polymorphism

Problems with Polymorphism

Interface

Why use an interface?

public interface Person {
	String getName();
	String getEmail();
}

public class User implements Person {
	private String name;
	private String email;
	
	public User(String name, String email) {
		this.name = name;
		this.email = email;
	}
	
	@Override
	public String getName() {
		return name;
	}
	
	@Override
	public String getEmail() {
		return email;
	}
}

These are my notes from the Low-Level Design (LLD) course I took at Scaler.

Check Python, Java and Go code on Github Repo

Tags: System-Design, Software-Engineering