Polymorphism

Baran Aslankan
BAU Yazılım ve Bilişim Kulübü
3 min readDec 3, 2021

Hey guys today i am going to be writing about one of the important subjects in Java called “Polymorphism”. It’s going to be a short review by me.

What exactly is Polymorphism ?

Poly word means many so it’s like many forms. But what does many forms mean in Java ?

Let’s see it in an example.

Example

Suppose that we have a student population and this population separates by gender. In this case student class is our parent class and we have 2 child classes called boys and girls.

public class Student{

public void msg() {
System.out.println("I'm a student.");
}
}
class Test{
public static void main(String[] args) {
Student st=new Student();
st.msg();
}
}

Our student class has a method that prints something, in the main method if we run this code the output is going to be this:

Now let’s create the child classes, since they are going to be the child of the student, we can call this method on them too.

public class Student{

public void msg() {
System.out.println("I'm a student.");
}
}
class Boys extends Student{

}
class Girls extends Student{

}
class Test{
public static void main(String[] args) {
Boys boy=new Boys();
Girls girl=new Girls();
boy.msg();
girl.msg();
}
}

Now we created the two child classes and called the method from the parent class and the output is going to be this:

Now we can write the same method for each of the child class and change the structure a little bit (overriding).

public class Student{

public void msg() {
System.out.println("I'm a student.");
}
}
class Boys extends Student{
public void msg() {
System.out.println("I'm a male student.");
}
}
class Girls extends Student{
public void msg() {
System.out.println("I'm a female student.");
}
}
class Test{
public static void main(String[] args) {
Boys boy=new Boys();
Girls girl=new Girls();
boy.msg();
girl.msg();
}
}

We overrode the “msg” method for each of the child class and called them in the main method, the output is going to be this:

We can even overload a method and use it.

public class Student{

public void msg() {
System.out.println("I'm a student.");
}
}
class Boys extends Student{
public void msg() {
System.out.println("I'm a male student.");
}
public void msg(int age) {
System.out.println("I am "+age+" years old. ");
}
}
class Girls extends Student{
public void msg() {
System.out.println("I'm a female student.");
}
}
class Test{
public static void main(String[] args) {
Student st=new Student();
Boys boy=new Boys();
Girls girl=new Girls();
boy.msg();
girl.msg();
st.msg();
boy.msg(21);
}
}

Here i overloaded “msg” method and added a parameter into it, and the output is going to be this:

So with polymorphism we can get multiple outputs under one method call.

That was all from me today, i hope i did good, see you on the next writing :)

--

--