Home  >  Article  >  Java  >  Variables in interfaces and extension

Variables in interfaces and extension

Barbara Streisand
Barbara StreisandOriginal
2024-10-06 06:11:31683browse

Variáveis em interfaces e extensão

Implicit variable declaration:

  • Variables declared in an interface are automatically public, static and final.
  • Useful for creating shared constants in large programs.

Code example:


// Interface que contém constantes
interface IConst {
    int MIN = 0;
    int MAX = 10;
    String ERRORMSG = "Boundary Error";
}

class IConstD implements IConst {
    public static void main(String[] args) {
        int nums[] = new int[MAX];
        for (int i = MIN; i < 11; i++) {
            if (i >= MAX)
                System.out.println(ERRORMSG);
            else {
                nums[i] = i;
                System.out.print(nums[i] + " ");
            }
        }
    }
}



Note: Although useful for constants, this technique can be controversial.

Interfaces can be extended

Inheritance in interfaces:

  • Interfaces can inherit other interfaces with the extends keyword.
  • A class that implements a derived interface must implement all the methods of the entire interface chain.

Code example:


// Interface A
interface A {
    void meth1();
    void meth2();
}

// Interface B estende A
interface B extends A {
    void meth3();
}

// Classe que implementa A e B
class MyClass implements B {
    public void meth1() {
        System.out.println("Implement meth1().");
    }

    public void meth2() {
        System.out.println("Implement meth2().");
    }

    public void meth3() {
        System.out.println("Implement meth3().");
    }
}

class IFExtend {
    public static void main(String[] args) {
        MyClass ob = new MyClass();
        ob.meth1();
        ob.meth2();
        ob.meth3();
    }
}



Important: If you remove the implementation of meth1(), a compilation error will occur as all interface methods must be implemented.

The above is the detailed content of Variables in interfaces and extension. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn