Bundle data and behavior, hide details, ensure security.
Inherit attributes, extend or modify functionality, promote code reuse.
Subclass: A class that inherits from another class. Subclasses can have multiple subclasses beneath them.
Superclass: A class that is inherited by another class.
Java supports single inheritance only (each class can inherit from only one parent class).
Method Override: Child class can rewrite a method inherited from parent class.
//People=Parent Class
public class People{
protected String name; //set up attribute
protected int age;
protected String address;
-----------------------------
public People(){//defalut constructor
this.name="A person";
this.age=0;
this.address="Taiwan";
--------------------------------
public People(String name, int age ,String address){
this.name=name;
this.age= age;
this.address=address;
}
public void walk(){
System.out.println("Walking");
}
public void sleep(){
System.out.println("Sleeping");
}
public void printHello(){
System.out.println("Hello from ppl class");
}
//--------subclass =Teacher
public class Teacher extends People{
private String subject;//Only need to add own attribute
public Teacher(String name, int age ,String address, String subject){
//child class inner constructor does not involve constructor
//Automatically run People.defult
super(name, age, address);
this.subject=subject;
}
public void teach(){
super.printHello();//inheritance from ppl class
System.out.println("Teaching "+subject);
}
@Override
public void walk(){
System.out.println("A stu walking like a bosss");//change content
}
}
Different implementations for same method, enhance flexibility and extensibility.
Compile-time Polymorphism
Also known as method overloading.
Within the same class, multiple methods can be defined with the same name but different parameter lists.
During compilation, the compiler determines which specific method to call based on the provided parameter information.
Runtime Polymorphism
Also known as method overriding.
Inheritance allows a subclass to override (rewrite) a method of its parent class to achieve different behavior.
During runtime, the appropriate method is called based on the actual object type.
public static void main (String[] args) {
//Polymorphism can use superclass來當datatype
//parent class
People S1=new Student("Annie",20,"CA",39);
People S2=new Student("Jenny",21,"TX",39);
People T1=new Teacher("John",50,"CA","Java");
//array
People[] people=new People[10];
people[0]=S1;
people[1]=S2;
people[2]=T1;
for(int i=0;i<3;i++){
System.out.println(people[i].name);//Annie, Jenny, John
}
//ArrayList
ArrayList<People> people=new ArrayList<>();
people.add(S1);
people.add(S2);
people.add(T1);
}