Polymorphism

From: Marc-Andre Michel (nosferatu_1_1_at_yahoo.com)
Date: 07/31/04


Date: 31 Jul 2004 06:50:21 -0700

Hi,

Could somebody tell me why the following code doesn't work ?

I presume the reason is that the type to cast to is not known at
compile time. If this is the reason,
what is your suggestion so A() can call the right method for the right
object type ?

public class A {
   public A(Object obj) {
      foo(obj); //ERROR
   }

   public void foo(String s) {
      //...print a string
   }

   public void foo(Collection c) {
      //...print a collection of strings
   }

   public static void main(String[] args) {
      String s = "my string";
      A a1 = new A(s);

      ArrayList l = new ArrayList();
      l.add("s1");
      l.add("s2");
      l.add("s3");
      A a2 = new A(l);
   }
}

Thanks,

Marc



Relevant Pages

  • Whidbey C# Generics/Iterators Question
    ... to break the compiler/runtime with my first Generics/Iterators attempt. ... reason I am posting it here is that I might be wrong, in which case, please ... public void Add ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Strange code in Queue class in .NET framework
    ... method of the generic Queue class in the .NET framework. ... public void Enqueue ... One possible reason for this might be as a sort of clever "high bandpass ...
    (microsoft.public.dotnet.framework)
  • skip super.paintComponent()
    ... there a compelling reason for that or can I rely on the proper execution of ... class MyFirstComponent extends javax.swing.JComponent ... public void paintComponent ...
    (comp.lang.java.programmer)
  • Re: Polymorphism
    ... If this is the reason, ... > public void foo{ ... which tests if its argument is a String or Collection and call the ...
    (comp.lang.java.programmer)
  • Re: Dynamic casting in c#
    ... should be cast to. ... The reason I don't know at compile time is because ... The whole purpose is for a persistence layer that stores/loads any ...
    (microsoft.public.dotnet.framework)