ホームページ  >  記事  >  Java  >  Java の最後のキーワード

Java の最後のキーワード

WBOY
WBOYオリジナル
2024-08-30 15:22:49604ブラウズ

この投稿では、Java の別の Final キーワードを見ていきます。 Java 言語で、他のクラスや変数による使用や変更に制限を適用するために使用されるキーワードです。このキーワードを使用すると、その変数またはメソッドに対する将来の変更を許可せず、それを定数として扱うようにインタプリタに指示します。以下の 3 つのシナリオで使用できます:-

広告 このカテゴリーの人気コース 財務モデリングと評価 - 専門分野 | 51 コースシリーズ | 30 回の模擬テスト

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

  1. 変数: 変数を Final として宣言すると、その変更が他の値または参照を参照するように制限されます。
  2. メソッド: メソッドを Final として宣言すると、子クラスでのそのメソッドのオーバーライドが制限されます。
  3. クラス: クラスを Final として宣言すると、そのクラスの継承が防止されます。

適切なコーディング慣行に従って、これらのキーワードは常に大文字で宣言することが推奨されます。

Java の Final キーワードの構文

このキーワードは以下の 3 つの方法で使用できます:-

1.変数

Java の変数は、その値の変更を制限する変数として宣言できます。以下の 3 つの方法のいずれかで宣言できます -

構文:

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
注- 参照変数は、別のオブジェクトへの参照を保持できないように静的として宣言することもできます。ただし、オブジェクトの内部性質により、参照は変更される可能性があります。

final String Builder sb= new StringBuilder(“LetsLearn”);

2.メソッド

final キーワードで宣言されたメソッドは、final メソッドと言われます。 Final メソッドはその子クラスによってオーバーライドできません。つまり、子クラスのメソッドは親クラスに存在する Final メソッドの定義を変更できません。親クラスで定義されたメソッドの実装がすべての子クラスでも従う必要がある場合、そのメソッドをfinalとして宣言する必要があります。

構文:

final int my1(){
//method defination
}

3.クラス

final キーワードをクラスで使用して、それを最終クラスにすることもできます。つまり、特定のクラスを他のクラスで拡張したり継承したりすることはできません。

構文:

final class myClass{
/member variables and member functions.
}

Final キーワードは Java でどのように機能しますか?

final キーワードは、継承時のクラス、メンバー、または変数のオーバーライドを制限するのに役立ちます。

1.最終変数

変数をfinalとして宣言すると、継承されたクラス内の変数の値への変更が制限されます。最終変数は 1 回だけ初期化できるため、そのまま使用する必要があります。したがって、最終変数を初期化する必要があります。これは主に、定数クラス変数を作成するために static とともに使用されます。

例:

final int a =0;

参照変数を Final として宣言することもできます。この場合、1 つの参照変数が異なるオブジェクトを参照することはできません。しかし、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 を使用して別の配列を参照しようとすると、コンパイラはエラーをスローします。したがって、ここで word-final 配列を使用すると、配列メンバーに任意の変更を加えることができますが、変数が他のオブジェクトを参照することは許可されないことを意味します。

覚えておくべきこと

コンパイル時のエラーを防ぐために、最終変数の初期化が必要です。 C++ の const 変数とこれらの最終変数との間には、const 変数を初期化する必要がないという違いがあります。最終変数を初期化するには 3 つの方法があります -

  • 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。