Programing

Java로 가상 함수 / 메소드를 작성할 수 있습니까?

lottogame 2020. 6. 14. 10:23
반응형

Java로 가상 함수 / 메소드를 작성할 수 있습니까?


C ++에서와 같이 Java로 가상 메소드 를 작성할 수 있습니까?

또는 유사한 동작을 생성하는 적절한 Java 접근 방식을 구현할 수 있습니까? 몇 가지 예를 들어 주시겠습니까?


에서 위키 피 디아

에서 자바 , 모든 비 정적 방법이 기본적으로 있습니다 " 가상 함수. "는 표시 만 방법 final 키워드 와 함께 무시 될 수없는, 개인 방법 상속되지이다 비가 상 .


Java로 가상 함수를 작성할 수 있습니까?

예. 실제로 Java의 모든 인스턴스 메소드는 기본적으로 가상입니다. 특정 방법 만 가상이 아닙니다.

  • 클래스 메소드 (일반적으로 각 인스턴스는 특정 메소드에 대한 vtable에 대한 포인터와 같은 정보를 보유하지만 여기서는 인스턴스를 사용할 수 없기 때문에).
  • 전용 인스턴스 메소드 (다른 클래스가 메소드에 액세스 할 수 없으므로 호출 인스턴스는 항상 정의 클래스 자체의 유형을 가지므로 컴파일 타임에 명확하게 알려짐)

여기 몇 가지 예가 있어요.

"정상"가상 기능

다음 예제는 다른 답변에서 언급 한 wikipedia 페이지 이전 버전 에서 가져온 것입니다.

import java.util.*;

public class Animal 
{
   public void eat() 
   { 
      System.out.println("I eat like a generic Animal."); 
   }

   public static void main(String[] args) 
   {
      List<Animal> animals = new LinkedList<Animal>();

      animals.add(new Animal());
      animals.add(new Fish());
      animals.add(new Goldfish());
      animals.add(new OtherAnimal());

      for (Animal currentAnimal : animals) 
      {
         currentAnimal.eat();
      }
   }
}

class Fish extends Animal 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a fish!"); 
   }
}

class Goldfish extends Fish 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a goldfish!"); 
   }
}

class OtherAnimal extends Animal {}

산출:

나는 일반적인 동물처럼 먹는다.
나는 물고기처럼 먹는다!
나는 금붕어처럼 먹는다!
나는 일반적인 동물처럼 먹는다.

인터페이스가있는 예

Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.

For example:

interface Bicycle {         //the function applyBrakes() is virtual because
    void applyBrakes();     //functions in interfaces are designed to be 
}                           //overridden.

class ACMEBicycle implements Bicycle {
    public void applyBrakes(){               //Here we implement applyBrakes()
       System.out.println("Brakes applied"); //function
    }
}

Example with virtual functions with abstract classes.

Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:

abstract class Dog {                   
    final void bark() {               //bark() is not virtual because it is 
        System.out.println("woof");   //final and if you tried to override it
    }                                 //you would get a compile time error.

    abstract void jump();             //jump() is a "pure" virtual function 
}                                     
class MyDog extends Dog{
    void jump(){
        System.out.println("boing");    //here jump() is being overridden
    }                                  
}
public class Runner {
    public static void main(String[] args) {
        Dog dog = new MyDog();       // Create a MyDog and assign to plain Dog variable
        dog.jump();                  // calling the virtual function.
                                     // MyDog.jump() will be executed 
                                     // although the variable is just a plain Dog.
    }
}

All functions in Java are virtual by default.

You have to go out of your way to write non-virtual functions by adding the "final" keyword.

This is the opposite of the C++/C# default. Class functions are non-virtual by default; you make them so by adding the "virtual" modifier.


All non-private instance methods are virtual by default in Java.

In C++, private methods can be virtual. This can be exploited for the non-virtual-interface (NVI) idiom. In Java, you'd need to make the NVI overridable methods protected.

From the Java Language Specification, v3:

8.4.8.1 Overriding (by Instance Methods) An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

  1. C is a subclass of A.
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
  3. Either * m2 is public, protected or declared with default access in the same package as C, or * m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

Yes, you can write virtual "functions" in Java.


In Java, all public (non-private) variables & functions are Virtual by default. Moreover variables & functions using keyword final are not virtual.

참고URL : https://stackoverflow.com/questions/4547453/can-you-write-virtual-functions-methods-in-java

반응형