Ambiguous inheritance in Java?

Hello, everyone,
I have heard through preventing from inheriting from multiple classes, Java is free of ambiguous inheritance (so called diamond inheritance). For example, class B derives from class A, class C derives from class A and class D derives from both class B and C, if class B and class C both overwrite the same method of class A, when invoking this method from class D, it will be ambiguous (method from class B or class C?).
I thought Java is free of this, but I have written a sample which has such ambiguous.
public interface Foo1 {
     void Fun();
public interface Foo2 {
     void Fun();
public class FooImpl implements Foo1, Foo2 {
     public void Fun() {
          // TODO Auto-generated method stub
}In class FooImpl, it has a method Fun which its super interface Foo1 and Foo2 both have. And suppose some clients will use FooImpl by Foo1 or Foo2 (other than using FooImpl itself), and they have to use the unified implementation of class FooImp, other than specifc implementation of Fun for Foo1 and Fun for Foo2. Is that ambiguous?
And suppose some clients will use FooImpl and they will invoke Foo function of class FooImpl, but they do not know whether it is Foo for Foo1 or Foo for Foo2. Even though Fun in interface Foo1 and Foo2 have no concrete implementation, the same function in different interface is possible to have different meanings, isn't it? How will they know which one they are using? Is that also ambiguous?
Thanks in advance,
George

as per the JLS
"It is possible for an interface to inherit more than
one method with the same signature (�8.4.2). Such a
situation does not in itself cause a compile-time
error. The interface is considered to inherit all the
methods. However, a compile-time error occurs if, for
any two such inherited methods, either they have
different return types or one has a return type and
the other is void. (The throws clauses do not cause
errors in this case.)"The problem isn't compilation errors, but semantic errors. Just because two methods share the same name doesn't mean they do the same thing. One framework could have an interface with a method called "eatsShootsAndLeaves" that tells a client supplied object to eat, shoot and leave. Another could have the same method to test if a client object eats shoots and leaves. Both might return a boolean. The compiler would be happy. There would be no way to implement one method that satisfied the requirements of both frameworks.

Similar Messages

  • Constructors and Inheritance in Java

    Hi there,
    I'm going over access modifiers in Java from this website and noticed that the following output is displayed if you run the snippet of code.
    Cookie Class
    import javax.swing.*;
    public class Cookie {
         public Cookie() {
              System.out.println("Cookie constructor");
         protected void foo() {
              System.out.println("foo");
    }ChocolateChip class
    public class ChocolateChip extends Cookie {
         public ChocolateChip() {
              System.out.println("ChocolateChip constructor");
         public static void main(String[] args) {
              ChocolateChip x = new ChocolateChip();
              x.foo();
    }Output:
    Cookie constructor
    ChocolateChip constructor
    fooI've been told that constructors are never inherited in Java, so why is "Cookie constructor" still in the output? I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?
    If you can shed any light on this, I would greatly appreciate it.
    Many thanks!

    896602 wrote:
    I've been told that constructors are never inherited in JavaThat is correct. If they were inherited, that would mean that, just by virtue of Cookie having a c'tor with some particular signature, ChocoChip would also "automatically" have a c'tor with that same signature. However, that is not the case.
    , so why is "Cookie constructor" still in the outputBecause invoking a constructor always invokes the parent class's c'tor before any of our own c'tor's body executes, unless the first statement is this(...), to invoke some other c'tor of ours. If this is the case, eventually down the line, some c'tor of ours will not have an explicit this(...) call. It will either have an explicit super(...) call, or no call at all, which ends up leading to the compiler generating a call to super().
    Note that the ability to call super(...) does not mean that that c'tor was inherited.
    I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?Yes, it is. As I pointed out above, if we don't explicitly call this(...) or super(...), then a call to super() is inserted by the compiler.

  • Inheritance in Java

    I have a little confusion regarding inheritance in Java... or perhaps the general concept... I was trying to write polymorphic code and I encountered this question...
    When a class inherits from another class, all the member variable is supposed to be inherited right? So, if I have something like:
    abstract class super{
    private SomeObject someObj;
    public abstract void foo();
    class sub extends super{
    public void foo(){
    someObj = new SomeObject();
    the class sub does not know about someObj. I tried different visibility for someObj but none worked...
    Something I have not tried, but might as well settle my question with inheritance here, is that if the super class were a concrete class, are all member variables inherited into its subclasses regardless of the member variables' visibility?
    Can someone clear my confusion? Thanx!

    I changed the visibility to protected and then public and it still would not compile... I think there might be something to do with the abstract.
    However, I remember that long time ago (I had this question for a while) I tested the concept with concrete classes and it seems that the private member variable is not inherited...
    That confused me quite a bit because I thought that when a parent class's member variable was private, a sub-class's object has no access to that variable of an instance of the parent class. But the subclass should have inherited it and should have its own copy of that variable. And when the visibility was protected, that's when an object of the subclass has access to that variable of an object of the parent class...
    I think the confusion comes from if visibility is meant for the class or for the instances of the class...

  • Reference to Timer is ambiguous, both class java.uti

    C:\g\Frame1.java:1776: reference to Timer is ambiguous, both class java.util.Timer in java.util and class javax.swing.Timer in javax.swing match
              Timer timer;
    My timer here refer to the one in java.util.Timer. How can I make to so that the timer refer to the one in java.util?
    Regards,
    Ng

    use the complete class name:
    import java.util.*;
    import javax.swing.*;
    public class Test
    java.util.Timer myTimer = new java.util.Timer(...);

  • Simulating Multiple Inheritance in Java

    Problem:
    I am trying to obfuscate code and create wrapper classes to access code implementation. Problem is that some parameters in methods have different types. (i.e.
    public class Example{
    ExampleImpl exampleImpl;
    public void setExample(Problem exam) {
    exampleImpl.setExample(exam); //complile error
    //error message: problemImpl is not of type problem
    public class ExampleImpl {
    public void setExample(ProblemImpl exam) {
    //do something
    The objects Problem and ProblemImpl are abstract class that provode some implementation.
    I know I have to sumulate multipule inheritance but its really have to changed the abstract classes to inherate each other. Problem with that is the ProblemImpl abstract class will be obfuscated.
    Any suggestions.

    Not quite following you but perhaps
    java.lang.reflect.proxy
    could be of service

  • Multiple inheritance in Java

    Why it is sometimes said that interfaces provide a form of multiple inheritance?
    Do you agree that interfaces can provide multiple inheritance? Explain.
    Some people say that Java does not support multiple inheritance, and others: a class can implement more than 1 interface. Isn't that multiple inheritance?
    Thanks

    >
    Some people say that Java does not support multiple
    inheritance, and others: a class can implement more
    than 1 interface. Isn't that multiple inheritance?Sort of, but you don't inherit any implementation from an interface.

  • No multiple inheritance in Java. Interfaces used.

    Hi,
    In java a class can extend only one class while the interface can extend any number of interfaces.
    Class extending only one class avoids multiple inheritance.
    Can you explain me the reason of avoiding this in classes and allowing interfaces to extend any number of interfaces ?

    Hi,
    In java a class can extend only one class while the
    interface can extend any number of interfaces.
    Class extending only one class avoids multiple
    inheritance.
    Can you explain me the reason of avoiding this in
    classes and allowing interfaces to extend any number
    of interfaces ?The real question is: do you have a need for multiple inheritance?
    If so, I would be glad to hear about this concrete problem.

  • Abt "import" statement & Inheritance in Java

    Hi, All
    As we (Java Programmers) know we'll be using "import java.Math.*" or similar for importing custom/Java packages.
    If i have suppose imported "import java.math.BigDecimal;" in a Class 'A' & and iam extending this class 'A' in another class 'B', if i want to use any method from 'BigDecimal' here in this class(i.e., in class 'B') again i need to import "import java.Math.BigDecimal; " .
    so, my question is :
    1) When we import in one class a package and same package in another class does java import it twice (or) what it does?
    2) when I extend a class , why don't this import facility don't get extended.(I think u got my point.)
    PS: If any problems in this mail technical or what so ever, iam sorry.
    Thanks in advance.

    Importation is just a compiler trick. It has nothing to do with runtime.
    The separation of sources files brings the necessity of repeated imports from file to file.
    You can verify this if you create one source file and put several classes in it: you won't have to import
    more than once.
    so, my answers are :
    1) Each time the compiler encounters an import package.Class statement, it checks the CLASSPATH for the class existence and loads the class definition.
    When a reference to the class is done anywhere in the following statements, the compiler checks the referenced entity (member, method...) against the class definition.
    2) If the extending class is contained in the same source file, then only one import will be needed.
    Hope this helped,
    Regards.

  • Mulitiple Inheritance in java

    Please help me in implementing this condition using java
    we have a parent
    abstract class Person.
    we have two classes
    Class Teacher extends Person
    and
    Class Student extends Person
    this structure cannot be modified as of now.
    Now i need to write a class "TeacherStudent" which has both Teacher and Student Properties.
    i have a method in Teacher class to compute salary that takes a instance of Teacher as parameter and another method to compute grade in Student that takes an instance of Student as parameter. i must be able to pass the new class written to both this methods.
    HOW TO ACHEIVE THIS IN JAVA? CAN ANYONE HELP

    I am really sorry for misguiding you and everybody else. You are right! Interfaces cannot extend classes. On the otherhand they can extend interfaces.
    I remember seeing some programs where they used the 'extends' keyword as in "interfaceA extends interfaceB" and I was mistaken that the extends word is only used with classes. Hence I was pretty sure that interfaces can extend classes.
    However upon writing some sample code, the compiler slapped me black and blue for doing such a thing :)
    Thanks for helping me discover this fact!

  • Class members don't override via inheritance in Java?

    Consider following code:
    class A
    protected int v=1;
    void print()
    System.out.println(v);
    class B extends A
    protected int v=2;
    public class m
    public static void main(String args[])
    B kl=new B();
    kl.print();
    What do you think, what should be the program's output?
    It is "1" - I think in C++ it would be "2" (I am not sure of this). Why the member variable "v" doesn't override the one from parent class in "print" method? Do you think it is ok?
    Consider changing B class definition to this:
    class B extends A
    protected int v=2;
    B() { v=3; }
    The output is still "1",
    but:
    class B extends A
    // protected int v=2;
    B() { v=3; }
    And the output is "3".
    So we have two different variables: A.v and B.v.
    Shouldn't be only one there, depending on the class of the object?

    Considder the following code.
    public class a
       int a;
       public a()
          a = 1;
       public int a()
          return a;
       public int a(a a)
          a.a = a.a++;
          if(this.a == a.a)
             return a();
          else
             return a.a;
    }Are you surprised that it actually compiles? Do you have any doubt about the behavour? Do you think it is smart to reuse the symbol a? Do you think it is smart to reuse the symbol v? Because that is what you do. You have two different integers, both with the name v. Then it gets confusing. My advice: Give them different names!

  • SWIG - C++/Java and multiple interface inheritance - SWIG typemaps

    In C++ I have the following. Can someone explain how to use SWIG typemaps to accomplish multiple interface inheritance in Java? I understand there is a javainterfaces typemap built into SWIG however I am such a newb with SWIG I really don't know where to start.
    class IRemoteSyncIO
    public:
      virtual ~IRemoteSyncIO () {}
    protected:
      IRemoteSyncIO () {}
    private:
      IRemoteSyncIO (const IRemoteSyncIO&);
      IRemoteSyncIO& operator= (const IRemoteSyncIO&);
    class IRemoteAsyncIO
    public:
      virtual ~IRemoteAsyncIO () {}
    protected:
      IRemoteAsyncIO () {}
    private:
      IRemoteAsyncIO (const IRemoteAsyncIO&);
      IRemoteAsyncIO& operator= (const IRemoteAsyncIO&);
    class RemoteMpe : public IRemoteSyncIO, public IRemoteAsyncIO
    }Thanks!

    Actually now I understand what you mean.... Ok, now I am going to modify the problem slightly and add Interface2 into the picture. The new code is:
    interface Interface1<SelfType extends Interface1<SelfType>>
    interface Interface2
    class Superclass implements Interface1<Superclass>
    class Dependant<Type extends Interface1<Type>>
       public static <Type extends Interface1<Type> & Interface2> Dependant<Type> getInstance(Class<Type> c)
         return new Dependant<Type>();
    class Subclass extends Superclass implements Interface2
      public Subclass()
        Dependant<Subclass> dependant = Dependant.getInstance(Subclass.class);
    }Now, previously I could replace:
    Dependant<Subclass> dependant = Dependant.getInstance(Subclass.class);
    with
    Dependant<Superclass> dependant = Dependant.getInstance(Superclass.class);
    and it solved the problem, but now that Type must implement Interface2 I cannot.
    The reason I added this requirement is that this is actually what is going on in my applicationI had made mistakely omited this detail from the original use-case.
    Can you think up of a possible solution to this new use-case?
    Thanks,
    Gili

  • Multiple Inheritance problem persists in Interfaces

    Hi,
    I tentatively made a program and found that multiple inheritance problem of C++ persists even with interfaces. Although this is definetely a special case but I want to know what is this problem known as( i know that this is perhaps known as diamond problem in C++). And is there a way out of this thing.
    interface one
         int i=10;
    interface two
         int i=20;
    interface z extends one,two
    public class xyz implements z
         public static void main(String [] a)
         System.out.println(i);
    }O/P
    D:\Education\Java\JavaStudyRoom\Applets>javac xyz.java
    xyz.java:16: reference to i is ambiguous, both variable i in one and variable i
    in two match
    System.out.println(i);
    *^*
    *1 error*
    Thanks for replying

    suvojit168 wrote:
    I tentatively made a program and found that multiple inheritance problem of C++ persists even with interfaces. Although this is definetely a special case but I want to know what is this problem known as( i know that this is perhaps known as diamond problem in C++). And is there a way out of this thing. This is not the so called diamond inheritance problem. What you have here is an ordinary name clash. And as has been noted you can resolve it by qualifying which constant you're referring to, like
    System.out.println(one.i);
    For the diamond inheritance problem to apply both the one and the two interfaces would need to inherit a common ancestor (that's how the diamond is formed). Furthermore the common anscestor would need to carry implementation which would then be inherited two ways, once via one and once via two. This is the diamond inheritance problem Java is avoiding by allowing single inheritance of implementation only.
    P.S. My previous post was posted my mistake.

  • Reference to class List is ambiguous

    Hello,
    I've started to make my first java program in which I use AWT.
    When I compile the file, it gave me this error:
    "reference to List is ambiguous, both class java.awt.List in java.awt and class java.util.List in java.util match"
    So I use some tools from the java library: java.util ( f.e. arrays)
    and I use of course the library: java.awt
    Now when I try to make a list:
    f.e.
    List data = new List(10,false);
    The program doesn't know if I want to use the method List, from AWT or UTIL
    In fact, I want to use this from AWT.
    How can I make that clear.
    Thx

    It will probably work if you add "import java.awt.List;" to your imports. If that doesn't do it, you will need to specify which List when you declare or instantiate it. For example, if you now have
    List list = new List(10,false);
    Then change it to
    java.awt.List list = new java.awt.List(10,false);

  • A little question about inheritance

    Can someone explain this to me?
    I have been reading about inheritance in Java. As I understand it when you extend a class, every method gets "copied" to the subclass. If this is so, how come this doesn't work?
    class inherit {
        int number;
        public inherit(){
            number = 0;
        public inherit(int n){
            number = n;
    class inherit2 extends inherit{
        public inherit2(int n, int p){
            number = n*p;
    class example{
        public static void main(String args[]){
            inherit2 obj = new inherit2();
    }What I try to do here is to extend the class inherit with inherit2. Now the obj Object is of inherit2 class and as such, it should inherit the constructor without parameters in the inherit class or shouldn't it ??? If not, then should I rewrite all the constructors which are the same and then add the new ones??

    I believe you were asking why SubClass doesn't have the "default" constructor... after all, shouldn't SubClass just have all the contents of SuperClass copy-pasted into it? Not exacly. ;)
    (code below... if you'd like, you can skip the first bit, start at the code, and work your way down... depending on if you just started, the next bit may confuse rather than help)
    Constructors are special... interfaces don't specify them, and subclasses don't inherit them. There are many cases where you may not want your subclass to display a constructor from it's superclass. I know this sounds like I'm saying "there are many cases where you won't want a subclass to act exactly like a superclass, and then some (extend their functionality)", but its not, because constructors aren't how an object acts, they're how an object gets created.
    As mlk said, the compiler will automatically create a default constructor, but not if there is already a constructor defined. So, unfortunatley for you, there wont be a default constructor made for SubClass that you could use to create it.
    class SuperClass { //formerly inherit
    int number;
    public SuperClass () { //default constructor
    number = 0;
    public SuperClass (int n) {
    number = n;
    class SubClass extends SuperClass { //formerly inherit2
    //DEFAULT CONSTRUCTOR, public SubClass() WILL NOT BE ADDED BY COMPILER
    public SubClass (int n, int p) {
    number = n*p;
    class Example {
    public static void main(String [] args) {
    //attempted use of default constructor
    //on a default constructorless subclass!
    SubClass testSubClass = new SubClass();
    If you're still at a loss, just remember: "Constructors aren't copy-pasted down from the superclass into the subclass!" and "Default constructors aren't added in if you add your own constructor in" :)
    To get it to work, you'd have to add the constructor you used in main to SubClass (like doopsterus did with inheritedClass), or use the constructor you defined in SubClass for when you make a new one in main:
    inherit2 obj = new inherit2(3,4);
    Hope that cleared things up further, if needed. By the way, you should consider naming your classes as a NounStartingWithACapital, and only methods as a verbStartingWithALowercase

  • ADF Business Component Type MAP Oracls vs Java

    what the advantages and disadvantages from each one map type
    thank in advance

    Take a look at this link in developer's guide:
    http://docs.oracle.com/cd/E16162_01/web.1112/e16182/bcintro.htm#sm0062
    The Java Extended for Oracle type map and the Oracle Domains type map handle numeric data differently. When you create a new application the default type map Java Extended for Oracle maps numeric data to the java.math.BigDecimal >class, which inherits from java.math.Number. The java.math.BigDecimal default matches the way the Fusion web application view layer, consisting of ADF Faces components, preserves alignment of numeric data (such as numeric values >displayed by ADF Faces input fields in a web page). Whereas the Oracle Domains type map, which maps numeric data to the oracle.jbo.domain.Number class, may not display the data with the alignment expected by certain ADF Faces >components. Aside from this alignment issue, the Oracle Domains type map remains a valid choice and applications without ADF Faces components will function without issue.Thanks,
    Navaneeth

Maybe you are looking for

  • How to open local system folder from the browser

    Hi All, I'm working on some stuff, wherein the user downloads the files from internet to his local machine. I'm able to catch the path of the folder where user wants to download the file from SaveAs prompt. Now my requirement is , i want to provide a

  • At New problem.

    Hello experts, I am currently having a problem with my At New statement. It is treating every field of the itab as a new record even though it is the same. for example, on the first loop the field tdline has a value of A then the at new will trigger.

  • Digitally signing pdf documents

    We want to digitally sign pdf documents that are generated in the printing service / AS. (rwclient is used on the client machines to access the printing service.) The digital sign should be on all generated pdf documents, with no intervention by the

  • JTree as cell renderer for JList

    I have an application that requires to display a list of tree-structured data. So I've used JTree a the cell renderer for the JList, and I can see a list of trees with that data in. However, the Jtree doesn't respond to Mouse messages, even if I disp

  • Archive transcode-0.6.12-1.pkg.tar.gz is corrupted - HELP?!

    Hey all, I've been trying to install transcode on arch 0.6. If i do pacman -Sy transcode I get an error error: archive transcode-0.6.12-1.pkg.tar.gz is corrupted I think it may be because my connection was interrupted during the download of transcode