Polymorphism and Overriding and Overloading

Asked 2 years ago, Updated 2 years ago, 80 views

When someone asked me what polymorphism is... Can overloading or overriding be the answer to that?

I think polymorphism needs to be added more than that. The one defined without the implementation of the method is called an abstract class And if you implement those methods in the lower class, is this also an override?

I don't think overloading is the right answer.

oop java

2022-09-21 20:23

1 Answers

The clearest way to express polymorphism is through abstraction classes.

public abstract class Human{
   ...
   public abstract void goPee();
}

This class is called an abstract class. Because in Human class, the method goPee() is not implemented. It's only defined in subclasses like Male and Female. Human is an abstract class.
So unlike Male and Female, human cannot create objects.

public class Male extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Stand Up");
    }
}
public class Female extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Sit Down");
    }
}

So we can implement Male and Female in this way. Polymorphism here is

public static void main(String[] args){
    ArrayList<Human> group = new ArrayList<Human>();
    group.add(new Male());
    group.add(new Female());
    // ... add more...

    // // tell the class to take a pee break
    for (Human person : group) person.goPee();
}

In this way, the data type of the group is Human, but the form of goPee() changes depending on which data type you create the object It's polymorphism.


2022-09-21 20:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.