Thursday, November 20, 2014

Knowledge: Object Oriented (OO)

1. What is polymorphism? difference between inheritance and polymorphism
Inheritance refers to using the structure and behavior of a superclass in a subclass. Polymorphism refers to changing the behavior of a superclass in the subclass.

Polymorphism is the ability of one method to have different behaviors depending on the type of the object it is being called on or the type of object passed as a parameter.
Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person, Student won't see it because its private, and private fields are not visible to subclasses.
Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student. It gets a bit tricky, but if you do something like
Person p = new Student();;
the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p isStudent.
2. Java Overloading vs Overriding
Overriding vs. Overloading are two confusing concepts for Java novice programmers.
Overloading is the situation that two or more methods in the same class have the same name but different arguments.
Overriding means having two methods with the same method name and arguments (i.e., method signature). One of them is in the Parent class and the other is in the Child class.

Override example:
class Dog{
    public void bark(){
        System.out.println("woof ");
class Hound extends Dog{
    public void sniff(){
        System.out.println("sniff ");
    public void bark(){
public class OverridingTest{
    public static void main(String [] args){
        Dog dog = new Hound();

No comments:

Post a Comment