JAVA 8の研究ノート - 章V

第5章クラス設計

1. Introduingクラスの継承

継承は、新しい子サブクラスは、自動的に親クラスで定義されたパブリックまたは保護されたプリミティブ、オブジェクトやメソッドが含まれるプロセスです。

Javaはシングル、マルチレベルの継承をサポートし、かつ、その複雑かつ困難な維持するために多重継承をサポートしていません。

Javaは複数のインタフェースを実装することができます。

Javaファイルには、多くのクラスを持っていますが、多くても1つのパブリッククラスにすることができます。

1)クラスの拡張

構文:

パブリック抽象クラスchildclassは} {parentclassを拡張します

子クラスは親クラスよりも「大きな」で、それは独自のプロパティと一緒に親クラスのすべてのプロパティを含んでいます。

公共およびデフォルトはトップレベルのクラスに適用されるのみアクセス修飾されている保護プライベートは内部クラス修飾子です。

2)Javaオブジェクトの作成

Javaでは、すべてのクラスが継承java.util.Object

クラスに定義された継承がない場合、オブジェクトクラスは、自動的にコードに挿入されます。

3)コンストラクタルールの作成

- すべてのコンストラクタの最初の文は)これを使用して、クラス内の別のコンストラクタの呼び出し()、またはスーパーを(使用して直接の親クラスのコンストラクタへの呼び出しにあります

- スーパー()の呼び出しは、コンストラクタの最初の文の後に使用することはできません

- いいえ、スーパー()またはコンストラクタで、この()呼び出した場合があった場合は、Javaが最初の文として無arguementスーパー()の呼び出しを挿入します

- 親が無arguementコンストラクタを持っていない場合、子は親のコンストラクタを明示的に呼び出す必要があり

4)メンバーを呼び出します

親のコンストラクタは最初にして、子のコンストラクタを実行すると呼ばれます。

どちらもこれスーパーは、親メンバーを呼び出すために使用することができますが、唯一これは、 子メンバーを呼び出すために使用することができます。

 

2.継承方法

1)メソッドのオーバーライド

あなたがメソッドをオーバーライドしようとすると、コンパイラは、次のチェックを実行します

- 子クラスのメソッドは、親クラスのメソッドと同じシグネチャを持つ必要があります。

- 子クラスのメソッドは、親クラスのメソッドよりも少なくとも同じacessible以上acessibleでなければなりません

- 子クラスのメソッドは、親クラスのメソッドにthrowed例外よりも新しいかボーダー例外をスローしないことがあり

- 子供メソッドの戻り値の型は同じか、親クラスのメソッドをサブクラスでなければなりません

2)Reclaringプライベートメソッド

Javaは、親クラスで定義されたプライベートメソッドと同じまたは修正署名と子クラスのprivateメソッドをreclareすることを許可します。

子クラスでこのメソッドは、親のバージョンのメソッドとは無関係の別個の独立した方法であるので、オーバーライドメソッドのルールのいずれも呼び出されません。

3)静的メソッドを隠します

それは混乱と困難な読み取ったコードにつながる原因、メソッドの隠蔽を避けるようにしてください。

あなたが親クラスで定義された静的メソッドと同じ名前のsigatureを持っている子クラスの静的メソッドを定義しようとすると、非表示の方法が起こります

Five checks when you try to hide a static method:

- four rules when you override a method

- both of methods defined in child and parent class have keyword static

4) Overriding A Method vs Hiding A Method

- The child version of an overriden method is always executed for an instance regardless of whether the method call is defined in a parent or child class. In this manner, the parent method is never used unless an explicit call to the parent class is referenced, using the syntax ParentClassName.method().

- The parent version of a hidden method is always executed when the method call is defined in the parent class.

5) Creatin final Method

The final method can NOT be overriden or hidden.

 

3. Inheriting Variables

Java does not allow variables to be overriden but instead hidden.

1) Hiding Variables

Similar to hiding a static method, the rules for accessing parent or child variables are quite similar.

Avoid to hide variables.

 

4. Creating Abstract Classes

An abstract class is a class that is marked with the keyword abstract and cannot be instantiated.

An abstract method is a method defined in an abstract class, it is marked with keyword abstract and no implementation is provided in the class in which it is declared.

example:

public abstract class Animal{

  public abstract String getName();  // no implementation

}

1) Defining An Abstract Class

Abstract class defination rules:

- cannot be instantiated directly

- defined with any number, including zero, of abstract or nonabstract methods

- may not mark with private or final

- an child abstract class inherits all the abstract methods of the parent class

- the first child concrete class must implement all the inherited abstract methods 

Abstract method defination rules:

- may only be defined in abstract classes

- not marked with final or private

- must not provide method body in the abstract where it is declared

- implementing an abstract method in a subclass follows the same rules as overriding a method

2) Creating a Concrete Class

A concrete class is the first nonabstract subclass that extends an abstract class and is required to implement all inherited abstract methods

3) Extend An Abstract Class

Abstract class can extend other abstract classes, are not required to implement any method.

 

5. Implementing Interface

An interface is an abstract data type that defines a list of public abstract methods that any class implementing the interface must provide.

syntax:

public abstract interface Well{

  public static final int MINIMUM_DEPTH = 2;

  public abstract int getMinimumDepth();  // public and abstract are assumed

}

1) Defining an Interface

Rules for defining an interface:

- interface are assumed to have abstract modifier

- interface cannot be instantiated directly

- interface is not required to have methods

- an interface may not marked with final

- all top-level interfaces are assumed to have public or default access modifier

- all nondefault methods are assumed to have modifier abstract and public in their defination

2) Inheriting an Interface

An interface can extend another interface, but cannot implement other interface.

An interface may extend multiple interfaces.

The only connection between interface and class is that class can implement interface.

- an interface that extends another interface, as well as an abstract class that implements an interface, inherits all of the abstract methods as its own abstract methods.

- the first concrete class that implements an interface, or extends an abstract class that implements an interface must provide implementation for all the abstract methods inheritted.

3) Methods and Multiple inheritance

example 1:

public interface A{

  public void eatPlants();

}

public interface B{

   public void eatPlants();  // have the same behavior with method in interface A

  public void eatMeat();

}

Public class Bear implements A, B{  // compile ok

  public void eatPlants();

  public void eatMeat();

}

 

example 2:

public interface A{

  public int eatPlants(int quantity);

} 

public interface B{

  public void eatPlants();   // different behavior with method in interface A

}

Public class Bear implements A, B{  // compile ok

  public int eatPlants(int quantity){  // implements methods inheritted from A and B

    System.out.print("eat plants" + quantity):

    return quantity;

  }

  public void eatPlants(){  // implements all the methods inheritted from A and B

    System.out.println("eat plants"):

  }

}

 

example 3:

public interface A{

  public int eatPlants();

} 

public interface B{

  public void eatPlants(); 

}

Public class Bear implements A, B{  // class doesn't permit two methods in a class with two same name and input parameters but different return types

  public int eatPlants(){  //  compile error

    System.out.print("eat plants: 10" ):

    return quantity;

  }

  public void eatPlants(){  //  compile error

    System.out.println("eat plants"):

  }

}

public abstract class Bear implements A, B{}  // compile error

public interface Bear extends A,B{}  // compile error

 

4) Interface Variables

- interface variables are assumed to be public, static and final

- the value of an variable must be set when it is declared

5) Default Interface Methods

A default method is a method defined within an interface with the keywords default in which the method body is provided.

Rules for default interface methods:

- A default method may only be declared within an interface and not within a class or an abstract class

- A default method must be marked with keyword default, and must have the method body

- A default method may not be marked to be static, final or abstract, as it may be used or overriden by a class that implements the interface

- Like all methods in the interface, a default method is assumed to be public and will not compile if marked with private or protected

When an interface extend another interface, it have three ways to deal with default methods:

- ignore it,  default implementation will be used

- override it with default method

- redeclare it as an abstract method

When a class implements an interface, it have two ways to deal with default methods:

- ignore it, default implementation will be used

- override it

example:

public interface HasFins{

  public default int getNumOfFins(){

    return 4;

  }

  public default double getLongestFinLength(){

    return 20.0;

  }

  public default boolean doFinsHaveScales(){

    return true;

  }

}

 

public interface SharkFamily extends HasFins{

  public default int getNumOfFins(){  // overrides method

    return 8;

  }

  public double getLongestFinLength();  // redeclare it as an abstract method

  public boolean doFinsHaveScales(){  // compile error, overrides but not have default keyword

    return false;
  }

}

6) Default Methods and Multiple Inheritance

- If a class extends two interfaces that have default methods with the same name and signature, the compile will throw an exception.

- But if the subclass overrides the duplicate default methods, the code will compile.

- This holds true even for abstract classes that implements multiple interfaces.

example:

public interface Walk{

  public default int getSpeed(){

    return 5;

  }

}

public interface Run{

  public default int getSpeed(){

    return 10;

  }

}

public class Cats implements Walk, Run{  // compile error

  public static void main(String[] args){

    System.out.println(new Cats().getSpeed());

  }

}

 

public class Cats implements Walk, Run{  // compile ok

  public int getSpeed(){

    return 1;

  }

   public static void main(String[] args){

    System.out.println(new Cats().getSpeed());

  }

}

 

7) Static Interface Methods

A static interface method defined in an interface is not inheritted in any classes that implements the interface

- marked as public

- the name of the interface is used to refer to an static interface method

- method body is optional provided

A class that implements two interfaces containing static methods with same sigature will still compile, because the static interface methods are not inheritted by the subclass and must be accessed with a reference to the interface name.

example:

public interface Hop{

  static int getJumpHeight(){

    return 8;

  }

}

public class Bunny implements Hop{

  public void printDetails(){

    System.out.println(Hop.getJumpHeight());  // interface name is used to refer to an static interface method

  }

}

 

6.  Understanding Polymorphism

Java supports polymorphism. To be more precise, a Java object may be accessed using a reference with the same type as the object, a reference that is a superclass of the object, or a reference that defines an interface the object implements, either directly or through a superclass.

Once the object has been assigned to a new reference type, only the methods and variables available to that reference type are callable on the object without an explicit cast.

example:

public class Primate {

  public boolean hasHair() {

    return true;

  } }

public interface HasTail {

  public boolean isTailStriped();

}

public class Lemur extends Primate implements HasTail {

  public boolean isTailStriped() {

    return false;

  }

  public int age = 10;

  public static void main(String[] args) {

    Lemur lemur = new Lemur();  // a reference to object type

    System.out.println(lemur.age);  // 10

    HasTail hasTail = lemur;    // a reference to an interface that the class implements

    System.out.println(hasTail.isTailStriped());  // false

    Primate primate = lemur;  // a reference to a class that the class extends

    System.out.println(primate.hasHair());  // true

  }}

1) Object vs Reference

In Java, all objects are accessed by reference, so as a developer you never have direct access to the object itself.

Changing the reference type doesn't change the object in the memory, it only change the accessibilities of the object's properties.

- the type of the object determines which properties exist within the object in memory.

- the type of the reference to the object determines which methods and variables are accessible to the Java program.

2) Casting Objects

Basic rules when casting objects:

- Casting an object from a subclass to a superclass doesn't require an explicit cast

- Casting an object from a superclass to a subclass requires an explicit cast

- The compiler will not allow casts to unrelated types

- Even when the code compiles without issue, it may throw an exception at runtime if the object being casted is not actually an instance of that class

example 1:

public class Bird{}
public class Fish{

  public static void main(String[] args){

    Fish fish = new Fish();

    Bird bird = (Bird) fish;  // unrelated class

  }

}

example 2:

public class Rodent{}

public class Capy extends Rodent{

  public static void main(String[] args){

    Rodent rodent = new Rodent();

    Capy capy = (Capy) rodent;  // throws an classcastexception at runtime, since the rodent is NOT an instance of Capy

  }

}

Problem can be solved by adding if (rodent isinstanceof  Capy).

3) Virtual Methods

A virtual method is a method in which the specific implementation is not determined until runtime.

In fact, all non-final, non-static and non-private methods are considered as virtual methods, since any of them can be overriden at runtime.

4) Polymorphism Parameters

One of the most useful applications of polymorphism is the ability to pass instances of a subclass or interface to a method

example:

public class Rep(){

  public String getName(){

    return "Rep";

  }

}

public class Alli extends Rep(){

  public String getName(){

    return "Alli";

  }

}

public class Cro extends Rep(){

  public String getName(){

    return "Cro";

  } 

}

public class ZooWorker{

  public static void (Rep rep){  // can pass iobject of an subclass

    System.out.println("feeding" + rep.getName);

  }

  public static void main(String[] args){

    feed(new Alli());

    feed(new Cro());

    feed(new Rep());

    feed(null);  // null can always be passed as an object value, regardless of type

  }

}

 

If you are defining a method that will be accessible outside the current class, either to subclass of the current class or publicly to objects outside the current class, it is considered good coding practise to use superclass or interface type of input parameters whenever possible.

 

おすすめ

転載: www.cnblogs.com/shendehong/p/11626508.html