Javaでの継承:クラスとインタフェース

Javaの継承は、オブジェクト指向の概念におけるシンプルで強力なプロパティであり、親クラスの属性とメソッドを娘クラスに書き直すことができ、このようにして別のサブクラスも娘クラスから継承できます。Java では、すべてのクラスでこのプロパティを使用します。

Java で継承に使用されるキーワードは  extends です。多重継承は禁止されていますが、interfaces.

The Object class

プログラミングすると、次のようなメソッドがどこでも繰り返されていることに気付きます: toObject(), equals(), wait()...等。これは、Javaではすべてのクラスがスーパークラスを継承するためです。オブジェクト これは階層全体のルートです.

Javaのオブジェクト指向ツリー階層< / a>< / td><>
すべてのクラスは Object

Example

この例では、name 属性と address 属性を持つ person クラスを宣言しています。どちらのサブクラスも Person を継承します: 第 1 クラスの director と、追加の属性として salary.


class Person
{
public 文字列名;
public 文字列アドレス。
}
class Employee extends Person
{
int salary;
public Employee(文字列名, 文字列アドレス, int salary)
{
this.name=name;
this.address=address;
this.salary=salary;
}
}
class Director extends Person
{
public Director()
{
this.name= "name";
this.adresse= "アドレス";
}
}

note:
娘クラスは宣言されたメンバーを継承しますprotected および public のメンバーも継承します private 親クラスと同じパッケージ内にある場合

java

Person クラスを拡張して、そこからサブクラスに継承できます。 エンジニア、会計士、秘書...etc.

UML Employee Accounting Engineer

class Engineer extends Employee
{
public Engineer()
{
super("name","address",110);
}

public void concevoir(){System.out.println("私はエンジニアです");}
public void developper(){};
}

class Accountant extends Employee
{
public Accountant()
{
this.name= "name";
this.adresse= "アドレス";
this.salary = 3000;
}

public void manageAccounts(){};
public void gererLesBilans(){};
}
構造を階層の形で見ています。このツリーは、プログラムの構造を理解するのに役立ちます。Engineer と Employee の 2 つのクラスの違いは、親クラスのコンストラクタを直接呼び出す super キーワードを Engineer で使用している点です。デフォルトでは、super() は引数なしでメーカーを呼び出し、スーパー(p1, p2,...) は、引数を指定してコンストラクタを呼び出します。

super キーワードは、上位クラスのメソッドを呼び出すためにも使用されます。次に例を示します:


class Ingenieur_reseaux extends Employee
{
public Ingenieur_reseaux ()
{
super("name","address",3100);
}

public void concevoir(){
super.concevoir();
System.out.println("会社のネットワークアーキテクチャを設計しました");
}
}
super がない場合、コンストラクタIngénieur_réseauxで宣言された design() メソッドが engineer で宣言された design() メソッドの代わりに呼び出されるため、親メソッドを参照するにはキーワードを追加する必要があります  super.

Runtime:

私はエンジニアです
会社のネットワークアーキテクチャを設計しました

Java

多重継承はインターフェイスに許可されています。

interface print{
void print();
}
インターフェイス display{
void display();
}
interface interfaceIA extends print,display{
void imprimer_afficher();
}
class testIA implements interfaceIA{

void print(){System.out.println("Printing")};
void display(){System.out.println("印刷完了")};

public static void main(){
testIA test = new testIA();
test.print();
test.display();
}
}