Интерфейс Java: наследование, переопределение и перегрузка методов

это, кажется, работает

        static void Main(string[] args)
    {
        bool exit = false;
        List<float> grades = new List<float>();

        do
        {
            Console.WriteLine("1. Enter Grades");
            Console.WriteLine("2. Get Average");
            Console.WriteLine("3. My program");
            Console.WriteLine("4. exit");
            Console.WriteLine("");

            string input = Console.ReadLine();

            Console.WriteLine("");

            if (input == "1")
            {
                int totalGrades = 0;

                //User Input
                Console.WriteLine("How many grades do you want to enter? ");
                while (true)
                {
                    try
                    {
                        totalGrades = Convert.ToInt32(Console.ReadLine());
                        break;
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("This is not a valid number");
                        continue;
                    }
                }
                Console.WriteLine("");

                while (totalGrades > 0)
                {
                    while (true)
                    {
                        try
                        {
                            grades.Add(Convert.ToInt32(Console.ReadLine()));
                            totalGrades--;
                            break;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("This is not a valid number");
                            continue;
                        }
                    }
                }

                Console.WriteLine("");
            }
            else if (input == "2")
            {

                double average = grades.Average();

                if (average >= 90)
                {
                    Console.WriteLine($"The average is a {average} which is an A.");
                }
                else if (average >= 80)
                {
                    Console.WriteLine($"The average is a {average} which is an B.");
                }
                else if (average >= 70)
                {
                    Console.WriteLine($"The average is a {average} which is an C.");
                }
                else if (average >= 60)
                {
                    Console.WriteLine($"The average is a {average} which is an D.");
                }
                else
                {
                    Console.WriteLine($"The average is a {average} which is an E.");
                }

                Console.WriteLine("");

            }
            else if (input == "4")
            {
                exit = true;
            } else
            {
                Console.WriteLine("This is not an option");
            }
        }
        while (exit == false);
    }
7
задан akjain 18 May 2009 в 12:53
поделиться

4 ответа

In the following two interfaces methodA() is identically defined in terms of parameters (none) and return type (int). The implementation class at the bottom defines a single method with this exact signature. As it complies to both interfaces, you get no problem there - any calls made via a reference of type InterfaceA or InterfaceB will be dispatched to this implementation.

The second methodB() is defined as returning any subtype of Number (or Number itself) in InterfaceA. InterfaceB defines methodB() as returning an Integer which is a subtype of Number. The implementation class actually implements the method with Integer, thus complying to the contract of both InterfaceA and InterfaceB. No problem here either. The commented out case of methodB() being implemented as returning a Double however would not work: While it would satisfy the contract of InterfaceA, it would conflict with InterfaceB (which demands an Integer).

If InterfaceA and InterfaceB were also specifying (different) contracts for a methodC() (commented out in the example) this would be contradictory and create a compiler error. Implementing both signatures (differing only in return type) is not allowed in Java.

The above rules would also hold true if were to add any parameters to the methods. For simplicity I kept this out of the example.

public interface InterfaceA {
    public int methodA();
    public Number methodB();
    // public int methodC(); // conflicting return type
}

public interface InterfaceB {
    public int methodA();
    public Integer methodB();
    // public String methodC(); // conflicting return type
}

public class ImplementationOfAandB implements InterfaceA, InterfaceB {
    public int methodA() {
        return 0;
    }
    public Integer methodB() {
        return null;
    }
    // This would NOT work:
    // public Double methodB() {
    //     return null;
    // }
}
2
ответ дан 6 December 2019 в 19:41
поделиться
interface A {
    void method();
    Object returnMethod();
}
interface B {
    void method();
    B returnMethod();
}

class Impl implements A,B 
{
    void method() { }
    B returnMethod() { }
}

Как видите, Impl.method () реализует как A.method () , так и B.method () , а Impl.returnMethod () возвращает B , который является потомком Object , таким образом выполняя A.returnMethod () контракт тоже. Требуется ли последний тип возвращаемого значения, который не является родительским для типа возвращаемого значения B.returnMethod () , что было бы ошибкой компиляции, поскольку такая реализация не может существовать в Impl .

8
ответ дан 6 December 2019 в 19:41
поделиться
interface A
{
   void foo();
   //int bar(); <-- conflicts with B.bar() because of different return type
}

interface B
{
   void foo();
   //double bar(); <-- conflicts with A.bar() because of different return type
}

class C implements A, B
{
   void foo() // this implements A.foo() AND B.foo()
   {
      ...
   }
}
1
ответ дан 6 December 2019 в 19:41
поделиться

Это то, что вы имеете в виду?:

interface A {
    Object get();
}
interface B {
    Number get();
}

abstract class MyClass implements A, B {
    // Try to override A.get, but cause a compile error.
    public Object get() { return null; }
}

Такой метод в MyClass автоматически генерируется javac как метод синтетического моста. Вы должны реализовать один метод, возвращающий тип, совместимый со всеми реализованными / переопределенными методами (в данном случае Number / Integer / Double / и т. Д.).

1
ответ дан 6 December 2019 в 19:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: