> Java > java지도 시간 > 본문

Java의 최종 키워드

WBOY
풀어 주다: 2024-08-30 15:22:49
원래의
580명이 탐색했습니다.

이번 포스팅에서는 자바의 다양한 최종 키워드를 살펴보겠습니다. 자바 언어에서 다른 클래스나 변수에 의한 사용이나 수정을 제한하기 위해 사용하는 키워드입니다. 이 키워드를 사용하면 인터프리터에게 해당 변수나 메소드에 대한 향후 수정을 허용하지 않고 이를 상수로 처리하도록 지시합니다. 아래 3가지 시나리오에서 사용할 수 있습니다.-

광고 이 카테고리에서 인기 있는 강좌 재무 모델링 및 가치 평가 - 전문 분야 | 51 코스 시리즈 | 모의고사 30개

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

  1. 변수: 변수를 final로 선언하면 다른 값이나 참조를 참조하도록 수정이 제한됩니다.
  2. 메서드: 메소드를 final로 선언하면 하위 클래스에서 해당 메소드를 재정의하는 것이 제한됩니다.
  3. 클래스: 클래스를 final로 선언하면 해당 클래스의 상속이 방지됩니다.

좋은 코딩 관행에 따르면 이러한 키워드는 항상 대문자로 선언하는 것이 좋습니다.

Java의 최종 키워드 구문

이 키워드는 아래 3가지 방법으로 사용될 수 있습니다.-

1. 변수

Java의 변수는 값 변경을 제한하기 위해 변수로 선언될 수 있습니다. 아래 세 가지 방법 중 하나로 선언할 수 있습니다.

구문:

final int VAR1=21;//final variable
final int VAR2; //blank final variable
static final double DUMMY= 45.504;//final static variable
static final double PK;//blank final static variable
로그인 후 복사
참고-  참조 변수는 다른 객체에 대한 참조를 보유할 수 없도록 정적으로 선언될 수도 있습니다. 그러나 객체의 내부 특성상 참조가 변경될 수 있습니다.

최종 문자열 빌더 sb= new StringBuilder(“LetsLearn”);

2. 방법

final 키워드로 선언한 메소드를 final 메소드라고 합니다. final 메서드는 자식 클래스에 의해 재정의될 수 없습니다. 즉, 자식 클래스 메서드는 부모 클래스에 있는 final 메서드의 정의를 변경할 수 없습니다. 상위 클래스에 정의된 메소드의 구현을 모든 하위 클래스에서 따라야 하려면 해당 메소드를 final로 선언해야 합니다.

구문:

final int my1(){
//method defination
}
로그인 후 복사

3. 수업

최종 키워드를 클래스와 함께 사용하여 최종 클래스로 만들 수도 있습니다. 즉, 특정 클래스는 다른 클래스에서 확장되거나 상속될 수 없습니다.

구문:

final class myClass{
/member variables and member functions.
}
로그인 후 복사

Java에서 Final 키워드는 어떻게 작동하나요?

마지막 키워드는 상속 중에 클래스, 멤버 또는 변수의 재정의를 제한하는 데 도움이 됩니다.

1. 최종 변수

변수를 final로 선언한다는 것은 상속된 클래스의 변수 값에 대한 변경을 제한한다는 의미입니다. 최종 변수는 한 번만 초기화할 수 있으며 그대로 사용해야 합니다. 따라서 최종 변수를 초기화해야 합니다. 상수 클래스 변수를 생성하기 위해 주로 static과 함께 사용됩니다.

예:

final int a =0;
로그인 후 복사

또한 참조 변수를 final로 선언할 수도 있습니다. 이 경우 하나의 참조 변수는 다른 개체를 참조할 수 없습니다. 그러나 Java에서는 객체의 내부 상태가 변경될 수 있습니다. 최종 참조 변수는 이를 참조합니다. 따라서 참조 변수의 값을 변경할 수 있습니다. 이는 아래와 같이 최종 배열을 사용하는 것과 같습니다.-

코드:

class MyClass
{
public static void main(String args[])
{
final int myarr[] = {1, 2, 3, 4, 5};
for (int q = 0; q < myarr.length; q++)
{
myarr [q] = myarr [q]*10;
System.out.println(myarr [q]);
}
}
}
로그인 후 복사

출력:

Java의 최종 키워드

설명

여기서 배열 a1은 동일한 객체를 참조합니다. 배열 변수에는 해당 배열 요소가 저장된 메모리 위치의 시작 주소만 포함되어 있다는 것을 우리 모두 알고 있기 때문에 해당 개체의 값만 변경됩니다.

그리고 마찬가지로 동일한 배열 변수 a1을 사용하여 다른 배열을 참조하려고 하면 컴파일러에서 오류가 발생합니다. 따라서 여기서 단어 끝 배열을 사용한다는 것은 배열 구성원을 변경할 수 있지만 변수가 다른 객체를 참조하는 것은 허용되지 않는다는 것을 의미합니다.

기억할 점

컴파일 타임 오류를 방지하려면 최종 변수 초기화가 필요합니다. C++ const 변수와 const 변수를 초기화할 필요가 없는 최종 변수 사이에는 차이가 있습니다. 최종 변수를 초기화하는 방법에는 세 가지가 있습니다.

  • Initialize at the time of declaration itself: We can easily declare a final variable at the time of declaring it. In case it is not initialized, then that variable is considered a blank final variable, and either of the next 2 ways can help us initialize a blank final variable.
  • Using instance-initializer block: Inside this block or the constructor, a blank final variable can be easily initialized. While using a constructor to initialize, always remember to initialize the particular variable in all the available constructors.
  • Static Block: One can also use a static block to initialize the blank final variable. Static block is always triggered once for each class; thus, the variable value whose values are not meant to be altered can easily be initialized using this block.

Thus, the final keyword is used for those variables that need not change their value during the program’s execution. All the final variables created inside a method or block must be initialized there itself. Such type of variables is known as local final variables.

Explanation

In the below example, a variable I has been declared within the main function and initialised is considered a final local variable.

Code:

class myClass
{
public static void main(String args[])
{
// local final variable
final int i;
i = 20;
System.out.println(i);
}
}
로그인 후 복사

Output:

Java의 최종 키워드

2. Final Methods

A method declared as final can not be overridden in any of the subclasses, thus called a final method. The method needs to be declared as final if we require that the child classes follow the class’s same implementation.

Note- Final methods don’t need to be declared in the initial stage of inheritance(base class ). The method can be declared final in any subclass that we want further subclasses to follow the same definition.

Code:

class A{
void myMethod(){
//method definition
}
}
class B extends A{
final void  myMethod(){
//overrides the method in parent class
//runs successfully
}
}
class C extends B{
void  myMethod(){
//will throw error
}
}
로그인 후 복사

3. Final Classes

Classes declared as final can not be inherited by any other classes. Mentioning a  final keyword before the class name tells the compiler that this class’s definition can only be used as they are. No other classes can add their specifications to this definition or reuse its code. If one attempts to extend the final class, an error is thrown by the compiler indicating that this class is not meant to be extended. One can use final keywords in java in any for below 2 purposes:-

  1. The first is to prevent the inheritance of that class. E.g., all the Wrapper classes present java.lang package is final classes; therefore, we cannot extend them in our classes but can use it by declaring their objects. Any attempt to access those classes will result in an error by the compiler.
final class myParentClass
{
// member variables and member functions
}
// illegal extend.
class myChildClass extends parentClass
{
// <--COMPILE-ERROR—> Can't subclass A
}
로그인 후 복사
  1. The second use of final with classes is when one needs to create an immutable class, i.e. once the class’s object is created, we cannot change its content like the predefined String class. The class must be declared as final to make it immutable.

Note-

  • If a class is declared as final, then its member variables and member functions are also considered final by the compiler.
  • A class cannot be declared abstract where it depends on the child classes to complete its definition and final, which prevents the inheritance itself.

Examples of Final Keywords in Java

Below is the Different Example of Final Keyword in Java are:

1. Using Final Variable

In the below example, different variables are initialized using various methods. For example- the SECOND variable is initialized using a constructor, whereas THIRD is initialized using an initializer.

Code:

class myClass
{
final int FIRST = 5;
// a blank final variable
final int SECOND;
// another blank final variable
final int  THIRD;
FIRST =10; //illegal attempt to change the value of final variable
// a final static variable PI
// direct initialize
static final double MINVALUE = 3.141592653589793;
// a  blank final static  variable
static final double MAXRANGE;
{
THIRD = 25; // initializer block
}
static{
MAXRANGE = 200.3;
}
public myClass()
{
SECOND = -1;//needs to be initialised in every constructor
}
}
로그인 후 복사

Output:

Java의 최종 키워드

2. Using Final Methods

In the below example, abstract class myShape declares final methods getWidth and get eight those need not be overridden by the inherited classes. It also declares one abstract function whose implementation is mandatory in the subsequent classes. Thus the only the definition of an abstract function is implemented in a first child class and a second child class.

Code:

abstract class myShape
{
private double width;
private double height;
public myShape(double width, double height)
{
this.width = width;
this.height = height;
}
public final double getWidth() //override not allowed
{
return width;
}
public final double getHeight() //override not allowed
{
return height;
}
abstract double getArea(); //needs to be defined in the child class
}
class firstChildClass extends myShape
{
public firstChildClass(double width, double height)
{
super(width, height);
}
final double getArea()
{
return this.getHeight() * this.getWidth();
}
}
class secondChildClass extends myShape
{
public secondChildClass(double side)
{
super(side, side);
}
final double getArea()
{
return this.getHeight() * this.getWidth();
}
}
public class myClass
{
public static void main(String[] args)
{
myShape s1 = new firstChildClass(10, 20);
myShape s2 = new secondChildClass(10);
System.out.println("width of s1 : "+ s1.getWidth());
System.out.println("height of s1 : "+ s1.getHeight());
System.out.println("width of s2 : "+ s2.getWidth());
System.out.println("height of s2 : "+ s2.getHeight());
System.out.println("area of s1 : "+ s1.getArea());
System.out.println("area of s2 : "+ s2.getArea());
}
}
로그인 후 복사

Output:

Java의 최종 키워드

3. Using Final Classes

In the below program, we are using a final class Solid that defines a method to calculate the volume of a shape using its dimensions, but displaying the volume of a box is done using the inherited class’s printVol function. Shape As Solid is a final class; thus, class Shape will not be allowed to extend(or inherit) it. Thus, it uses Shape’s object to calculate the volume of any of Shape by just passing the arguments to the functions.

Code:

final class Solid {
public double getVol(double length, double width, double height) {
return length * width * height;
}
}
class Shape {
private float length;
private float width;
private float height;
Shape(float length, float width, float height) {
this.length = length;
this.width = width;
this.height = height;
}
public void printVol(Solid bObj) {
double volume = bObj.getVol(this.length, this.width, this.height);
System.out.println("Volume of the Shape: " + volume);
}
}
public class myClass {
public static void main(String[] args) {
Solid bObj = new Solid();
Shape obj = new Shape(5, 4, 3);
obj.printVol(bObj);
}
}
로그인 후 복사

Output: 

Java의 최종 키워드

Conclusion

The final keyword is used to prevent the classes, variables, and methods to be overridden by its child classes. It can also be used to make classes immutable that is restricting the change in the value of their objects. The final keyword check is always checked at the compile time only. It is a great utility to prevent the reuse of the defined variables, logic, and classes.

위 내용은 Java의 최종 키워드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!