วันเสาร์ที่ 17 กรกฎาคม พ.ศ. 2553

Overriding Method

Methods defined in a superclass can be overridden by methods defined in a subclass. Here is the definition:

Definition Overiding: Overriding refers to the introduction of an instance method in a subclass that has the same name,signature,and return type of a method in the superclass. Implementation of the method in the subclass replaces the implementation of the method in the superclass.

Overriding is different from overloading.Overriding is concerned with methods of different classes that have an inheritance relationship.In overriding,methods share the same name,signature,and return type.In contrast,overloaded methods are part of the same class,but have different signatures.

We can illustrate the distinction between overloading and overriding in the following manner. In

class A{
        public void m1(){
            //statement
        }
        public void m1(int i){
            //statement
        }
    }

class A contain two overloaded methods.An instance of A can access both methods,depending on the arguments of the method invocation,so

A a = new A();
a.m1();            //invoke m1()
a.m1(1);          //invoke m1(int)

Now,let us assume that we have the two classes

class B{
    public void m2(){
        //statement
    }
}
class C{
    public void m2(){
        //statement
    }
}

Implementation of method m2() in class B is overridden by another implementation of method m2() in class C. For a given object,one but not both of the implementations of method m2() is available, depending on the class of the object.

B b = new B();
C c = new C();
b.m2(); //invoke the m2() in class B
c.m2(); //invoke the m2() in class C

Overriding a method with another method of different signature or return type is not allowed.For example,the following code segment will cause a compilation error:

class B{
    public void m3(int i){
    }
}
class C{
    public void m3(char c){
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น