Looking For Anything Specific?

ads header

Polymorphism in JAVA || OOPS CONCEPT

 



In movies, the hero takes multiple roles .ok now, what is polymorphism?  simply we can say, one example of polymorphism is We,      because in the home we are very innocent .our mom thinks that how my child get on this world. but in school or friends zone we are like a ROWDY guy (bad guy). after getting the job we will be matured. so we take multiple roles.

So polymorphism is 

"one name but multiple forms" is a concept of  polymorphism. 

example 

    1.method name is same but we can apply for different type of arguments (overloading )

                    abs(int i)

                    abs(long l)

                    abs(float f)

    2.method signature is same but on parent class one type of implementation and child class  another type of implementation .(overriding)


                class P{

                    public void marry ()

                       {

                                    System.out.println("Mahalaxmi");

                        }

                }


                class C extends P {

                        public void marry ()

                            {

                                    System.out.println("anupama / pranitha");

                            }

                       }

    3.usage of parent reference to hold child objects is concept of polymorphism 

                        List l = new AL ();  

                        List l = new LL();

                         List l = new Stack ();

parent class reference can be used to hold child objects but using the reference we can call only the methods available in parent class .and we cant call child specific methods.

P  p = new C ();  // parent has m1 method and child has m2 method 

p.m1();    //This is valid 

p.m2();  .// This is invalid 

but using child reference we can call both parent and child class methods  

C c = new C ();  // parent has m1 method and child has m2 method 

c.m1();    //This is valid 

c.m2();  .// This is valid 


when should we go for parent reference to hold child objects ?

if we don't know exact run time types of object then we should go for parent reference .for example the first element present in the ArrayList can be any type it may be student object ,customer objec or String Object hence the return type of get method is Object which can hold any objects 

Object o = l.get(0);

but one disadvantage is 

by using parent reference we call only methods available in parent class and we cant call child specif methods  

we use parent reference to holdany child object 






 

                                         



Post a Comment

0 Comments