Programing

자바의 최종 대 C ++의 const

lottogame 2020. 6. 16. 21:48
반응형

자바의 최종 대 C ++의 const


튜토리얼 C ++ 프로그래머를위한 자바 그 (강조는 내 자신의) 말한다 :

final 키워드 는 C ++의 const와 거의 같습니다.

이 문맥에서 "거의"는 무엇을 의미합니까? 그들은 정확히 동일하지 않습니까?

차이점이 있다면 무엇입니까?


C ++ 표시에서 멤버 함수 constconst인스턴스에서 호출 될 수 있음을 의미합니다 . Java에는 이와 동등한 것이 없습니다. 예 :

class Foo {
public:
   void bar();
   void foo() const;
};

void test(const Foo& i) {
   i.foo(); //fine
   i.bar(); //error
}

값은 나중에 Java에서만 한 번만 지정할 수 있습니다.

public class Foo {
   void bar() {
     final int a;
     a = 10;
   }
}

Java에서는 합법적이지만 C ++에서는 합법적이지 않습니다.

public class Foo {
   void bar() {
     final int a;
     a = 10;
     a = 11; // Not legal, even in Java: a has already been assigned a value.
   }
}

Java와 C ++에서 멤버 변수는 각각 final/ 일 수 있습니다 const. 클래스 인스턴스 생성이 완료 될 때까지 값을 제공해야합니다.

Java에서는 생성자가 완료되기 전에 설정해야하며, 다음 두 가지 방법 중 하나로 수행 할 수 있습니다.

public class Foo {
   private final int a;
   private final int b = 11;
   public Foo() {
      a = 10;
   }
}

C ++에서는 const멤버쉽에 값 을 제공하기 위해 초기화 목록을 사용해야 합니다.

class Foo {
   const int a;
public:
   Foo() : a(10) {
      // Assignment here with = would not be legal
   }
};

Java에서는 final을 사용하여 무시할 수없는 것으로 표시 할 수 있습니다. C ++ (pre-C ++ 11)은이 작업을 수행하지 않습니다. 예 :

public class Bar {
   public final void foo() {
   }
}

public class Error extends Bar {
   // Error in java, can't override
   public void foo() {
   }
}

그러나 C ++에서 :

class Bar {
public:
   virtual void foo() const {
   }
};

class Error: public Bar {
public:
   // Fine in C++
   virtual void foo() const {
   }
};

멤버 함수를 표시하는 의미가 다르기 때문에 이것은 const좋습니다. 멤버 함수 중 하나만 사용하여 오버로드 할 수도 const있습니다 (C ++ 11에서는 멤버 함수를 최종으로 표시 할 수 있습니다 (C ++ 11 업데이트 섹션 참조).)


C ++ 11 업데이트 :

C ++ 11을 사용하면 finalJava와 같은 Java의 동일한 기능에 대해 동일한 의미를 갖는 클래스와 멤버 함수를 모두로 표시 할 수 있습니다 .

public class Bar {
   public final void foo() {
   }
}

public class Error extends Bar {
   // Error in java, can't override
   public void foo() {
   }
}

이제 C ++ 11에서 다음과 같이 정확하게 작성할 수 있습니다.

class Bar {
public:
  virtual void foo() final;
};

class Error : public Bar {
public:
  virtual void foo() final;
};

I had to compile this example with a pre-release of G++ 4.7. Note that this does not replace const in this case, but rather augments it, providing the Java-like behaviour that wasn't seen with the closest equivalent C++ keyword. So if you wanted a member function to be both final and const you would do:

class Bar {
public:
  virtual void foo() const final;
};

(The order of const and final here is required).

Previously there wasn't a direct equivalent of const member functions although making functions non-virtual would be a potential option albeit without causing an error at compile time.

Likewise the Java:

public final class Bar {
}

public class Error extends Bar {
}

becomes in C++11:

class Bar final {
};

class Error : public Bar {
};

(Previously private constructors was probably the closest you could get to this in C++)

Interestingly, in order to maintain backwards compatibility with pre-C++11 code final isn't a keyword in the usual way. (Take the trivial, legal C++98 example struct final; to see why making it a keyword would break code)


In Java the final keyword can be used for four things:

  • on a class or method to seal it (no subclasses / overriding allowed)
  • on a member variable to declare that is it can be set exactly once (I think this is what you are talking about)
  • on a variable declared in a method, to make sure that it can be set exactly once
  • on a method parameter, to declare that it cannot be modified within the method

One important thing is: A Java final member variable must be set exactly once! For example, in a constructor, field declaration, or intializer. (But you cannot set a final member variable in a method).

Another consequence of making a member variable final relates to the memory model, which is important if you work in a threaded environment.


A const object can only call const methods, and is generally considered immutable.

const Person* person = myself;
person = otherPerson; //Valid... unless we declared it const Person* const!
person->setAge(20); //Invalid, assuming setAge isn't a const method (it shouldn't be)

A final object cannot be set to a new object, but it is not immutable - there is nothing stopping someone from calling any set methods.

final Person person = myself;
person = otherPerson; //Invalid
person.setAge(20); //Valid!

Java has no inherent way of declaring objects immutable; you need to design the class as immutable yourself.

When the variable is a primitive type, final/const work the same.

const int a = 10; //C++
final int a = 10; //Java
a = 11; //Invalid in both languages

Java final is equivalent to C++ const on primitive value types.

With Java reference types, the final keyword is equivalent to a const pointer... i.e.

//java
final int finalInt = 5;
final MyObject finalReference = new MyObject();

//C++
const int constInt = 5;
MyObject * const constPointer = new MyObject();

You have some great answers here already, but one point that seemed worth adding: const in C++ is commonly used to prevent other parts of the program changing the state of objects. As has been pointed out, final in java can't do this (except for primitives) - it just prevents the reference from being changed to a different object. But if you are using a Collection, you can prevent changes to your objects by using the static method

 Collection.unmodifiableCollection( myCollection ) 

This returns a Collection reference that gives read-access to the elements, but throws an exception if modifications are attempted, making it a bit like const in C++


Java's final works only on primitive types and references, never on object instances themselves where the const keyword works on anything.

Compare const list<int> melist; with final List<Integer> melist; the first makes it impossible to modify the list, while the latter only stops you from assigning a new list to melist.


Aside from having certain and subtle multi-threading properties, variables declared final don't need to be initialized on declaration!

i.e. This is valid in Java:

// declare the variable
final int foo;

{
    // do something...

    // and then initialize the variable
    foo = ...;
}

This would not be valid if written with C++'s const.


According to wikipedia:

  • In C++, a const field is not only protected from being reassigned, but there is the additional limitation that only const methods can be called on it and it can only be passed as the const argument of other methods.
  • Non-static inner classes can freely access any field of the enclosing class, final or not.

I am guessing it says "roughly" because the meaning of const in C++ gets complicated when you talk about pointers, i.e. constant pointers vs. pointers to constant objects. Since there are no "explicit" pointers in Java, final does not have these issues.


Let me explain what I understood with an example of switch/case statement.

The values in each case statement must be compile-time constant values of the same data type as the switch value.

declare something like below (either in your method as local instances, or in your class as static variable(add static to it then), or an instance variable.

final String color1 = "Red";

and

static final String color2 = "Green";

switch (myColor) { // myColor is of data type String
    case color1:
    //do something here with Red
    break;
    case color2:
    //do something with Green
    break;
}

This code will not compile, if color1 is a class/instance variable and not a local variable. This will compile if color1 is defined as static final (then it becomes static final variable).

When it does not compile, you will get the following error

error: constant string expression required

keyword "const" mean that your variable is saved in ROM (with Microprocessor). in computer, your variable is saved in RAM area for Assembly code (read only RAM). it means that your variable is not in the writeable RAM include: static memory, stack memory and heap memory.

keyword "final" mean that your variable is saved in writeable RAM, but you notice to compiler that your variable is only change only one time.

//in java language you can use:
static final int i =10;
i =11; //error is showed here by compiler

//the same in C++ the same as follows
int i =10;
const int &iFinal = i;

iFinal = 11; //error is showed here by compiler the same as above

I think, "const" is bad in performance, so Java does not use it.

참고URL : https://stackoverflow.com/questions/4971286/javas-final-vs-cs-const

반응형