Runtime Polymorphism

Hi
Asper the code snippet below:
What is the advantage that we get by declaring the object as in Statement 1 over the declaration in Statement 2 below, when both obj1 and obj2 can perform all methods available in subclass B. Moreover as per what I know, obj1 can not access those methods of class B which are not available in class A whereas obj2 can perform all methods of class A as well as class B ???
Then why do programmers use Statement type of declaration???
Runtime polymorphism also occurs if I declare it in the Statement 2 way, the show() function as described in both classes gets overridden.
Can anyone read the problem statement carefully and really explain me why anyone would ever want to use Statement 1 declaration when there there is no harm in Statement 2 declaration and rather an advantage that obj2 can use all the class B's functions whereas obj1 might not be able to do so? Is there anything that I am missing here?????
Am a novice programmer, forgive me if I am missing something. Kindly clarify my doubt if you have time.
Class A{
   void show(){
      System.out.println("Am in A");
Class B extends A {
   void show(){
      System.out.println("Am in B.");
Class Test{
   public static void main(String[] args){
      A obj1 = new B();  // Statement 1
      B obj2 = new B();  // Statement 2
      obj1.show();
      obj2.show();
}

justgig8 wrote:
Runtime polymorphism also occurs if I declare it in the Statement 2 way, the show() function as described in both classes gets overridden.
Can anyone read the problem statement carefully and really explain me why anyone would ever want to use Statement 1 declaration when there there is no harm in Statement 2 declaration and rather an advantage that obj2 can use all the class B's functions whereas obj1 might not be able to do so? Is there anything that I am missing here?????In your limited example, there's really no non-trivial advantage. We had a long, drawn out argument about this recently, but basically it boils down to, "in general, if possible, code to the interface (or least concrete type)". In your example, it might be that main() becomes a long, complex method, and one day somebody tells you that it would work 20 times faster if you used a (C extends A) instead of a B. If you were using the first declaration, it'd be an easy switch. If you were using the second, it might not be.
But the real power of coding to the interface (and polymorphism in general) is for less trivial situations, where the choice of type is not fully encapsulated as it is in your example.

Similar Messages

  • How does java implements runtime polymorphism.?

    Hi all.
    we know how does runtime polymorphism take place in java.
    But my quesions is , how does java implement it internally.
    in C++, with the use of keyword virtual , complier decides to make a call at runtime using virtual table and Vptr.
    like in c++,
    class base {
    public:
    virtual void show(){
    cout<<"I am in base class"<<endl;
    class child : public base {
    public:
    void show(){
    cout<<" I am in child class"<<endl;
    int main(){
    base*p = new child();
    p->show();
    return 0;
    out put - I am in child class.
    but if we remove the virtual keyword then output
    I am in base class..
    We know how it happens
    but in java
    class base {
    void show(){
    System.out.println("I am in base class");
    class child extends base {
    void show(){
    System.out.println(" I am in child class");
    class demo {
    public static void main(string args[ ]){
    base b;
    child c = new child();
    b = c;
    b.show();
    output is - I am in child class
    but how can i bring the output as
    I am in base class ---
    complier knows that b is base reference so y doesnt it just use base version.

    if all methods are virtual..then we should always have runtime binding but we do have early biding too.
    shouldnt we able to call base verison using a base reference variable like in c++.
    May be I m mixing big times java n c++. But it seems to me as core java is much like c++ . The things u can do in c++ , u can do same in java in different ways.

  • Java supports runtime polymorphism?

    Java supports runtime polymorphism but fails if overridden method is a static method?

    As static method associated with a class (with all the instances) it may fail the runtime polymorphism.
    But I can see the overriding is still allowed. When I run the following code it runs perfectly without any error. I am not sure
    public class TestAnimal {
         public static void main(String[] args){
         Animal A = new Dog();
         A.bark();
    class Animal{
         public static void bark(){System.out.println("I don't know how to bark");}
    class Dog extends Animal{
         public static void bark(){System.out.println("barking");}
    I am not sure if bark() function is not overridden.
    Any thoughts?

  • What is runtime polymorphism

    what is runtime polymorphism

    Technical yes I know.
    Here's it in lay terms: Runtime Polymorphism is polymorphic code that is generated when the code is executed.
    Think in terms of class structure. You can have two or more derivitive classes (objects) of a parent (super) class (object). If you call a method upon one of these child classes (objects) and it is actually at run-time an instance of the super class (object), then the code which is executed is actually that of the super class and not of the child class.

  • Is this runtime polymorhpism?

    For an assignment i'm doing we must use runtime polymorhpism (dynamic dispatch). I have three classes, Encryption (superclass), Caeser and Mixed (subclasses). Encryption is an abstract class with an abstract method called encrypt of which Caeser and Mixed have their own unique implemenation. In the main method I instantiate two objects like so:
    Encryption caeser = new Caeser();
    Encryption mixed = new Mixed();
    and I invoke the encrpyt methods also within the main method like so, caeser.encrypt(), mixed.encrypt(). So is this still an example of runtime polymorphism even though my superclass is abstract?
    Cheers

    jag28 wrote:
    For an assignment i'm doing we must use runtime polymorhpism (dynamic dispatch). I have three classes, Encryption (superclass), Caeser and Mixed (subclasses). Encryption is an abstract class with an abstract method called encrypt of which Caeser and Mixed have their own unique implemenation. In the main method I instantiate two objects like so:
    Encryption caeser = new Caeser();
    Encryption mixed = new Mixed();
    and I invoke the encrpyt methods also within the main method like so, caeser.encrypt(), mixed.encrypt(). So is this still an example of runtime polymorphism even though my superclass is abstract?Yes this is an example of runtime polymorphism because the decision of which class to call with the method is decided during runtime.
    Mel

  • Compiletime or runtime

    what is compile time poly and runtime poly?.function overloading is called compile time poly and function overriding is called rutime poly .During compile time the syntax will be checked is this called compiled time ?.If it's rutime time is this called runtime polymorphism.

    class Area {
    //Square
    public float computeArea(int x) {
    return x*x;
    //Rectangle
    public float computeArea(int x ,int y){
    return x*y;
    public void printArea(){
    System.out.println(computeArea(4)); //compile time poly
    class CircleArea extends Area{
    public float computeArea(int x) {
    return (float)x*x*3.14;
    Area a = new CircleArea();
    float i = a.computeArea(); //run time poly
    phew!

  • Regarding polymorphism

    Hi
    I have doubt regarding polymorphism.Why we are calling oveloading is
    compiletime polymorphism and overridding is called runtime polymorphism.

    satishnarayan wrote:
    Hi
    I have doubt regarding polymorphism.Why we are calling oveloading is
    compiletime polymorphism and overridding is called runtime polymorphism.Because with overloading, the compiler knows exactly which method signature will be called, but with overriding, it's the JVM--the runtime environment--that discovers which class' version of the method will be called.
    public class Parent {
      // overloading
      public void foo(Object obj) { System.out.println("obj"); }
      public void foo(String str) { System.out.println("str"); }
      // overriding
      public void bar() { System.out.println("parent"); }
    public class Child extends Parent {
      public void bar() { System.out.println("child"); }
    Object obj1 = new Object(); // compiler only knows obj1 Object reference, not new Object()
    Object obj2 = "abc"; // compiler only knows obj2 Object reference, not that the object it points to at runtime will be a String
    String str = "xyz"; // compiler only knows String reference type for str variable
    Parent p1 = new Parent();
    p1.foo(obj1); // "obj"
    p1.foo(obj2); // "obj"
    p1.foo(str); // "str"
    Parent p2 = new Child();
    Child c = new Child();
    p1.bar(); // "Parent"
    p2.bar(); // "Child"
    c.bar(); // "Child"The compiler knows the type of the reference, but it doesn't know the class of the object that reference will point to at runtime. p2 = new Child(); could have been replaced with a method that randomly returns a Parent, a Child, or any other subclass of Parent. Whose version of the bar() method gets called is determined by what that runtime object is.
    With overloading, it doesn't matter what the runtime class of the object is. Which signature gets called is entirely determined by the compile-time types of the parameter references.

  • When to use polymorphism?

    hi
    What is the need of polymorphism?And what is the need of compile time polymorphism and runtime polymorphism?
    Thanks
    Jiten

    What is the need of polymorphism?Basically polymorphism is any language mechanisms that allows the same code to work with different types. There are many kinds of polymorphism but when people say polymorphism they usually mean subtyping. In Java you use class extension and interface implementation and method overriding to achieve it.
    And what is the
    need of compile time polymorphism and runtime
    polymorphism?It's a classification of different kinds of polymorphism based on when the polymorphism can be resolved, at compile- or run-time. Basically it's a technical issue you don't have to worry much about while programming.
    Subtyping is an example of runtime (or dynamic) polymorphism. The object type cannot be determined until the program is run.

  • Polymorphism and constants

    Hi all,
    I have a problem to do with polymorphism. I've written a simplified version of what's happening below (in the actual project I have many classes extending the base class):
    class ClassA {
         private final int TEST = 10;
    class ClassB extends ClassA {
         private final int TEST = 20;
         public static void main(String[] args) {
              ClassA bee = new ClassB();
              System.out.println(bee.TEST);
    }As you can see, the problem is I want to be able to access a constant from the base class, but have it return the value from the actual overriding class. The way I'm doing it now is to put a method like:
    public int getTest() {
         return TEST;
    }in every class, but this seems like a bit of a hack. Does anyone have a more elegant solution?
    Thanks,
    Eugene

    As you can see, the problem is I want to be able to
    access a constant from the base class, but have it
    return the value from the actual overriding class.Can't do it. Member variables are not runtime polymorphic. You'll have to use a getter method. Only non-private, non-final instance methods are runtime polymorphic in Java.

  • Question about polymorphism

    hi
    I've got a question regarding polymorphism in java:
    public class Test1 {
        public Test1() {
            Test3 t3=new Test2();
            t3.output();
            t3.value1=9; //not possible
        public static void main(String[] args) {
            new Test1();
    public class Test2 extends Test3 {
        public int value1=5;
        @Override
        public void output() {
            System.out.println("the value is "+value1);
    public class Test3 {
        public void output(){
            System.out.println("class: Test3");
    output of the program:
    the value is 5why do i have no access from "Test1" to the member variable "value1" which is initialized in class "Test2" although i'm calling the constructor "Test2()"?
    and why is the output of the program "the value is 5" although I've got no access to "value1" from "Test1" like i said before?

    becky3 wrote:
    why do i have no access from "Test1" to the member variable "value1" which is initialized in class "Test2" although i'm calling the constructor "Test2()"?Because the type of t3 is reference to Test3, and Test3 does not have a value1 variable. The compiler doesn't know that at runtime that reference is going to point to a subclass of Test3 that does have that variable.
    and why is the output of the program "the value is 5" although I've got no access to "value1" from "Test1" like i said before?Because that's how Java's runtime polymorphism works. When you call an overridden method, it's the runtime class of the object that determines whose version of that method gets called. Since the object is a Test2, it's Test2's implementation of the method that gets called. The caller and type of reference don't have to know about the internal details of that class. Only that it's a subclass of Test3, and therefore exposes all the same public instance members as Test3.

  • Runtime 'type' assignment

    Hi All,
    I have a specific requirement where I need to dynamically change the Target structure by changing the 'Type' attribute. The condition what  data-type should be held in 'Type' is determined at run time based on the source field. Ex. The attribute called 'animal' has type 'eagle' or 'camel' or 'whale'. Eagle, camel and whale have different data structures. Based on the source, I should be able to choose the type of animal and populate its parent node.
    Alternatively, I know I can create a animal of all 3 types and suppress the one's that are not applicable. But wanted to check if XI provides such runtime polymorphic capabilities.
    Regards,
    Keerti

    Hi Keerti,
        as per your requirement the source xml looks something like this
    <mt_source>
    <animal>
       <type> eagle</type>
       <property>bird</property>
       <p1></p1>
       <p2></p2>
    </animal>
    <animal>
       <type> camel</type>
       <property>animal</property>
       <p1></p1>
       <p2></p2>
    </animal>
    </mt_source>
    you can create target as this
    <mt_target>
    <eagle>
          <properties>bird</properties>
          <property>animal</property>
           <p1></p1>
    </eagle>
    <camel>
          <properties>animal</properties>
          <p2></p2>
    </camel>
    <whalel>
          <properties></properties>
           <p1></p1>
    </whale>
    <mt_target>
    The number of occurence of each <animal> may be set to 0 to unbounded in source message.
    In the target you need to set <eagle>,<camel>,<whale> each occurence set from zero to unbounded.
    Finally you can do graphical mapping as shown
    <type>------------------------
                                               ---------------equalsS-------creatif-------------------------eagle 
    constant("eagle")-----------
    regards
    Anupam

  • How do you apply Single Responsibility principle to a repository

    I am trying to apply "SOLID" whenever I can and try to use common sense and avoid a pattern when I see that a pattern is creating more problems than it's trying to solve. I don't want to apply a pattern and make life difficult for somebody else using
    my code just for the sake "I write patterns" if you see what I mean.
    Now I am struggling with one of the principles that I thought was the easiest to grasp: "SRP".
    How do you practically apply this principle to repositories?
    Let's suppose I have a
    IEmployeeRepository
    IUserRepository
    IProductRepository
    and commonly they will have methods like these:
    public interface IUserRepository
    User GetUser(int id);
    IEnumerable<User> GetAllUser();
    void DeleteUser(int id);
    same for employees and products.
    Are we saying that each of these method should be a class on it's own? even though at times we are talking a single line of code?

    Hello,
    "Are we saying that each of these method should be a class on it's own? even though at times we are talking a single line of code?"
    interface is not a method. It has its own definition and you can refer to here:
    http://msdn.microsoft.com/en-us/library/87d83y5b.aspx
    Any from your question I think you may still confused about the usage of interface. In this way, I will recommend you have a look at the following blog:
    http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
    "Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from different classes through the same Interface reference, whereas using virtual functions we can invoke functions from different classes in
    the same inheritance hierarchy through the same reference"
    With the blog you can check that code to see details about how to use interface.
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Why it is not overriding

    Hi,
    I m puzzled by the output of :
    public class MyClass2 {
    private void f() {
    System.out.println("private f()");
    public static void main(String[] args) {
    MyClass2 po = new Derived();
    po.f();
    class Derived extends MyClass2 {
    public void f() {
    System.out.println("public f()");
    output: private f(); why it is happening...... when it is said that at runtime base class's ref chk the object that it is holding & executes its method ...ie; runtime polymorphism ...but in above case ...can any body tell why it is not happening.......?
    Thanks in advance.....

    Read the OPs question again: The method of the base class is private and the method of the subclass is public, not the other way around!
    When you override the method, the signature must remain the same. You can change the access modifier but only to a less restricted one. That's what the OP did!
    So you can't make a public method private. Correct!
    But you could make a protected one private.Wrong! You could make a protected one public.
    @OP: private members are only visible in the class it defines - not in subclasses. So the subclass would not know that there is a method with the same signature and that it overrides this method!
    So what happens? If you redeclare a method in a subclass a method, which was private in the superclass, it hides the method of the superclass. Polymorphism does not apply when calling private methods!
    public static void main(String[] args) {
      MyClass2 po1 = new MyClass2();
      po1.f(); //-> calls private method of MyClass2; can only be called from within MyClass2; no polymorphism!
      MyClass2 po2 = new Derived();
      po2.f(); //-> calls private method of MyClass2 because po2 is declared as MyClass2; can only be called from within MyClass2; no polymorphism!
      Derived po3 = new Derived();
      po.f(); //-> calls public method of Derived, which *hides* the method of MyClass2
      MyClass2 po4 = new Derived();
      ((Derived) po).f(); // -> po4 is declared as MyClass2 but we explicitly cast it to Derived, so the method of Derived gets called.
    }Look up hiding for more information!
    -Puce

  • Inheritance related question

    class a{
         public void meth()
              System.out.println("In a");
    class b extends a{
         public void meth()
              System.out.println("In b");
    public class Test extends b{
         public static void main(String[]a)
    }can i call the a's meth() from Test without creating an instance of a? This might be a simple question and i think i cant create it, but if this is possible please tell me how to do it. also im not referring to runtime polymorphism. without using runtime polymorphism, can i access a's meth()? i know by calling super.meth() in b's meth() will solve it but i do not want to go that way.
    Thanks in advance,
    Geet

    meth is not a static method of the class a, so you can't really call it without instantiating class a.
    If you meant "can I call method meth in class a with an instance of class b?",(note that an instance of b is an instance of a) the answer is no as well, because your method from class b has overridden it... Note that you CAN call the method from class a from within class b (but not from Test), by using the keyword super.

  • Overriding Superclass's Instance Variables?

    Ideally, this is what I'd like to accomplish:
    public abstract class AbstractClass {
        public static final int variable = 0;
        public static int getVariable() {
            return variable;
    public class RealClass {
        public static final int variable = 2;
    }So that when I call RealClass.getVariable(), it returns 2 instead of 0. I know that using the above code won't work, but is there something that I'm missing that will make this possible? I thought about making the variable non-final, and just passing it up to the superclass via a constructor, but then I can't have a static method. Is there a way to get something close to this accomplished, without overriding the superclass's getVariable() method?

    No can do. Variables are not runtime polymorphic, nor are static methods.
    public abstract class AbstractClass {
        public abstract int getVariable();
    }

Maybe you are looking for