Java_Polymorphism Flashcards

1
Q

What is Polymorphism in Java? Give an example.

A

In the example below, we have created different types of Automobile using the InvetoryManager class taking a single class of Automobile which will refer to the similar type of objects. This is the idea of polymorphism.

  • It means a class has the same interface or set of methods but different implementation.
  • Polymorphism is the ability of anyone object(Automobile) to be referred by several different types of references.
  • Polymorphism is about substitutability. This principle provides OOP languages like Java with extreme code flexibility.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does polymorphism look on a stack?

A

Always try “is a” rule for checking the parent-child inheritance for a valid polymorphism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why use polymorphism?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Benefits of polymorphism.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is object casting? Give an example.

A

Remember that casting just changes reference, it will not completely change the assignment.

// Here getSalary was defined in child, so cannot access child's methods
        Person p1 = new Employee("Keerhti", "Dadige", 19900101, 123, 20010101);
        System.out.println("Full Name: " + p1.getFullName());
        //System.out.println("Full Name: " + p1.getFullName() + " Salary: " + p1.getSalary());//p1 cannot access getSalary
        //To resolve above, we can do Object casting
        // Object Casting
        System.out.println("Full Name: " + p1.getFullName() + " Salary: " + ((Employee)p1).getSalary());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to protect the object casting at runtime?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is an Object class in Java?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What happens when we append strings using + operator using String class?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Override the equals() method of Object class using an example to compare two objects?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly