Method Overriding

ปรมินทร์ หิรัญรัตนาธร 650710562

Method Overriding คือเมธอดชนิดหนึ่งที่สามารถสืบทอดได้ คือการสร้างเมธอดซ้ำในคลาสลูก โดยคลาสลูกสามารถปรับเปลี่ยนการทำงานของเมธอดจากคลาสแม่ได้ แต่ยังมีชื่อและพารามิเตอร์เดิมในคลาสลูก

Method Overriding in C#

Method Overriding ใน C# เป็นการที่เมธอดสามารถเรียกใช้ฟังก์ชันจากคลาสแม่ที่สืบทอดมา สร้างเมธอดที่สืบทอดลักษณะการทำงานมาโดยมีชื่อคลาส พารามิเตอร์และการรีเทิร์นเหมือนกันกับเมธอดในคลาสแม่, มีการรองรับ polymorphism, จะต้องมีระดับการเข้าถึงเดียวกัน

ตัวอย่าง

class base_class
{
    public void gfg();
}

class derived_class : base_class
{
    public void gfg();
}

class Main_Method
{
 static void Main()
 {
    derived_class d = new derived_class();
    d.gfg();
 }
}

ใน C# สามารถใช้คีย์เวิร์ด 3 ประเภทใน Method Overriding

- virtual keyword : ใช้เพื่อเปลี่ยนวิธีการ คุณสมบัติ ให้มีการแทนที่ในคลาสที่สืบทอดมา ตัวอย่าง

public virtual double Area()
{
    return x * y;
}

- override : ใช้ในเมธอดในคลาสลูก เพื่อให้สามารถปรับเปลี่ยนเมธอดเสมือนที่สืบทอดมาจากคลาสแม่ ตัวอย่าง

class base_class
{
    public virtual void gfg();
}

class derived_class : base_class
{
    public override void gfg();
}

- base Keyword : ใช้เพื่อเข้าถึงสมาชิกในคลาสแม่ที่สืบทอดมาเช่น เมธอด ฟิลด์ คอนสตรัคเตอร์ ตัวอย่าง

using System;  
public class Animal{  
    public string color = "white";  
}  
public class Dog: Animal  
{  
    string color = "black";  
    public void showColor()  
    {  
        Console.WriteLine(base.color);  
        Console.WriteLine(color);  
    }  
      
}  
public class TestBase  
{  
    public static void Main()  
    {  
        Dog d = new Dog();  
        d.showColor();  
    }  
}  

เอาท์พุต

Method Overriding in Java

Method Overriding ใน Java เป็นการที่คลาสลูกนำลักษณะการทำงานที่มีอยู่แล้วในคลาสแม่มาใช้ , มีการรองรับ polymorphism ,ในการใช้งานต้องระบุ @override เพื่อแสดงว่าเมธอดคลาสลูกเป็นการ overriding จากคลาสแม่

// Java program to demonstrate
// method overriding in java

// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    @Override void show()
    {
        System.out.println("Child's show()");
    }
}

// Driver class
class Main {
    public static void main(String[] args)
    {
        // If a Parent type reference refers
        // to a Parent object, then Parent's
        // show is called
        Parent obj1 = new Parent();
        obj1.show();

        // If a Parent type reference refers
        // to a Child object Child's show()
        // is called. This is called RUN TIME
        // POLYMORPHISM.
        Parent obj2 = new Child();
        obj2.show();
    }
}

เอาท์พุต

Parent's show()
Child's show()

กฎสำหรับ Java Method Overriding

1. Overriding and Access Modifiers สามารถทำให้เมธอดมีการเข้าถึงได้มากขึ้น แต่ไม่สามารถลดระดับการเข้าถึงได้ เพราะจะทำให้เกิดข้อผิดพลาดขณะคอมไพล์ได้

ตัวอย่าง

// A Simple Java program to demonstrate
// Overriding and Access-Modifiers

class Parent {
    // private methods are not overridden
    private void m1()
    {
        System.out.println("From parent m1()");
    }

    protected void m2()
    {
        System.out.println("From parent m2()");
    }
}

class Child extends Parent {
    // new m1() method
    // unique to Child class
    private void m1()
    {
        System.out.println("From child m1()");
    }

    // overriding method
    // with more accessibility
    @Override public void m2()
    {
        System.out.println("From child m2()");
    }
}

// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj1 = new Parent();
        obj1.m2();
        Parent obj2 = new Child();
        obj2.m2();
    }
}

เอาท์พุต

From parent m2()
From child m2()
  1. Final methods can not be overridden สามารถประกาศ final เพื่อไม่ให้เมธอดมีการ overridden

ตัวอย่าง

// A Java program to demonstrate that
// final methods cannot be overridden

class Parent {
    // Can't be overridden
    final void show() {}
}

class Child extends Parent {
    // This would produce error
    void show() {}
}

เอาท์พุต

13: error: show() in Child cannot override show() in Parent
    void show() {  }
         ^
  overridden method is final
  1. Static methods can not be overridden เมื่อมีการประกาศ static method ที่มีลักษณะเหมือนกันกับ static method ในคลาสแม่จะเรียกว่า method hiding

ตัวอย่าง

// Java program to show that
// if the static method is redefined by
// a derived class, then it is not
// overriding, it is hiding

class Parent {
    // Static method in base class
    // which will be hidden in subclass
    static void m1()
    {
        System.out.println("From parent "
                           + "static m1()");
    }

    // Non-static method which will
    // be overridden in derived class
    void m2()
    {
        System.out.println(
            "From parent "
            + "non - static(instance) m2() ");
    }
}

class Child extends Parent {
    // This method hides m1() in Parent
    static void m1()
    {
        System.out.println("From child static m1()");
    }

    // This method overrides m2() in Parent
    @Override public void m2()
    {
        System.out.println(
            "From child "
            + "non - static(instance) m2() ");
    }
}

// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj1 = new Child();

        // As per overriding rules this
        // should call to class Child static
        // overridden method. Since static
        // method can not be overridden, it
        // calls Parent's m1()
        obj1.m1();

        // Here overriding works
        // and Child's m2() is called
        obj1.m2();
    }
}

เอาท์พุต

From parent static m1()
From child non - static(instance) m2() 
  1. Private methods can not be overridden Private method จะไม่สามารถ overridden ได้เนื่องจาก Private method จะเข้าถึงได้เฉพาะในคลาสที่มันถูกประกาศเท่านั้น ทำให้คลาสลูกไม่สามารถเข้าถึงได้

ตัวอย่าง

class SuperClass {
    private void privateMethod()
    {
        System.out.println(
            "This is a private method in SuperClass");
    }

    public void publicMethod()
    {
        System.out.println(
            "This is a public method in SuperClass");
        privateMethod();
    }
}

class SubClass extends SuperClass {
    // This is a new method with the same name as the
    // private method in SuperClass
    private void privateMethod()
    {
        System.out.println(
            "This is a private method in SubClass");
    }

    // This method overrides the public method in SuperClass
    public void publicMethod()
    {
        System.out.println(
            "This is a public method in SubClass");
        privateMethod(); // calls the private method in
                         // SubClass, not SuperClass
    }
}

public class Test {
    public static void main(String[] args)
    {
        SuperClass obj1 = new SuperClass();
        obj1.publicMethod(); // calls the public method in
                             // SuperClass

        SubClass obj2 = new SubClass();
        obj2.publicMethod(); // calls the overridden public
                             // method in SubClass
    }
}

เอาท์พุต

This is a public method in SuperClass
This is a private method in SuperClass
This is a public method in SubClass
This is a private method in SubClass
  1. The overriding method must have the same return type เมธอดที่ถูก overriding ในคลาสลูกต้องมีชนิดการรีเทิร์นที่เหมือนกันกับเมธอดแม่ เรียกว่า covariant return type

ตัวอย่าง

class SuperClass {
    public Object method()
    {
        System.out.println(
            "This is the method in SuperClass");
        return new Object();
    }
}

class SubClass extends SuperClass {
    public String method()
    {
        System.out.println(
            "This is the method in SubClass");
        return "Hello, World!";
    }
}

public class Test {
    public static void main(String[] args)
    {
        SuperClass obj1 = new SuperClass();
        obj1.method();

        SubClass obj2 = new SubClass();
        obj2.method();
    }
}

เอาท์พุต

This is the method in SuperClass
This is the method in SubClass
  1. Invoking overridden method from sub-class สามารถเรียกใช้เมธอดในคลาสแม่ในการ overriding method โดยใช้ super keyword

ตัวอย่าง

// A Java program to demonstrate that overridden
// method can be called from sub-class

// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    @Override void show()
    {
        super.show();
        System.out.println("Child's show()");
    }
}

// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj = new Child();
        obj.show();
    }
}

เอาท์พุต

Parent's show()
Child's show()

Overriding and Constructor ไม่สามารถ override คอนสตรัคเตอร์ได้เนื่องจากคอนสตรัคเตอร์ในคลาสแม่และลูกจะไม่สามารถมีชื่อเดียวกันได้

Overriding and Exception-Handling มีกฎ 2 ข้อดังนี้

1. หากคลาสแม่ไม่มีการประกาศ Exception วิธีที่คลาสลูก overriden จะประกาศ Exception โดยไม่ได้รับการตรวจสอบ

ตัวอย่าง

import java.io.*;    
class Parent{   
  
  // defining the method   
  void msg() {  
    System.out.println("parent method");  
    }    
}    
    
public class TestExceptionChild extends Parent{    
  
  // overriding the method in child class  
  // gives compile time error  
  void msg() throws IOException {    
    System.out.println("TestExceptionChild");    
  }  
  
  public static void main(String args[]) {    
   Parent p = new TestExceptionChild();    
   p.msg();    
  }    
}    
  1. ถ้าคลาสแม่มีการประกาศ Exception วิธีที่คลาสลูก overriden จะไม่สามารถประกาศ Exception หลักได้ สามารถประกาส Exception แบบเดียวกับคลาสลูกได้

ตัวอย่าง

import java.io.*;    
class Parent{    
  void msg() {  
    System.out.println("parent method");  
  }    
}    
    
class TestExceptionChild1 extends Parent{    
  void msg()throws ArithmeticException {    
    System.out.println("child method");    
  }    
  
  public static void main(String args[]) {    
   Parent p = new TestExceptionChild1();    
   p.msg();    
  }    
}  

Overriding and Abstract Method Abstract methods ใน interface หรือ abstract class เป็นเมธอดปล่าวๆ มีไว้เพื่อให้ overridden โดย concrete classes กำหนดการทำงานของตัวเอง

Overriding and Synchronized/strictfp Method Synchronized/strictfp ไม่มีผลต่อกฎของ overridden

Method Overriding in Python

Method Overriding ใน Python วิธีการดำเนินจะถูกกำหนดโดยออบเจ็คต์ที่เรียกใช้ ออบเจ็คต์จะเป็นตัวกำหนดว่าเวอร์ชั่นใดจะถูกเรียกใช้ หากออบเจ็คต์เรียกใช้ในคลาสแม่เวอร์ชันของคลาสแม่จะถูกเรียกใช้ ถ้าออบเจ็คต์เรียกใช้ในคลาสลูกเวอร์ชั่นในคลาสลูกจะถูกเรียกใช้

ตัวอย่าง

# Python program to demonstrate 
# Defining parent class 
class Parent(): 
    
    # Constructor 
    def __init__(self): 
        self.value = "Inside Parent"
        
    # Parent's show method 
    def show(self): 
        print(self.value) 
        
# Defining child class 
class Child(Parent): 
    
    # Constructor 
    def __init__(self): 
        super().__init__()  # Call parent constructor
        self.value = "Inside Child"
        
    # Child's show method 
    def show(self): 
        print(self.value) 
        
# Driver's code 
obj1 = Parent() 
obj2 = Child() 

obj1.show()  # Should print "Inside Parent"
obj2.show()  # Should print "Inside Child"

เอาท์พุต

Inside Parent
Inside Child

Method Overriding with Multilevel and Multiple Inheritance

- Mutiple Inheritance : คือการที่คลาสได้รับการสืบทอดจากคลาสแม่มากกว่าหนึ่งคลาส

ตัวอย่าง

class Parent1(): 
    def show(self):  
        print ("Inside Parent1") 
class Parent2(): 
    def display(self):  
        print ("Inside Parent2")
class Child (Parent1, Parent2):  
    def show(self):  
        print ("Inside Child")  
obj = Child ()  
  obj. show ()  
obj. display ()  

เอาท์พุต

Inside Child
Inside Parent2

- Multilevel Inheritance : มีลักษณะการสืบทอดที่มีหลายระดับของคลาส มีความสัมพันธ์ในฐานะลูกและหลานเช่น คลาส A สืบทอดไปคลาส B คลาส B สืบทอดไปคลาส C

ตัวอย่าง

class Parent (): 
    def display(self):  
        print ("Inside Parent")
class Child (Parent):  
    def show(self):  
        print ("Inside Child")
class GrandChild (Child): 
    def show(self):  
        print ("Inside GrandChild")           
g = GrandChild ()     
g.show()  
g.display()

เอาท์พุต

Inside GrandChild
Inside Parent

Calling the Parent’s method within the overridden method เรียกใช้เมธอดคลาสแม่ได้ใน overridden method มี 2 วิธี

1. Using Classname : เรียกใช้โดยการใช้ Parent classname.method ภายใน overridden method

ตัวอย่าง

# Python program to demonstrate 
# calling the parent's class method 
# inside the overridden method 
class Parent(): 
    
    def show(self): 
        print("Inside Parent") 
        
class Child(Parent): 
    
    def show(self): 
        
        # Calling the parent's class 
        # method 
        Parent.show(self) 
        print("Inside Child") 
        
# Driver's code 
obj = Child() 
obj.show() 

เอาท์พุต

Inside Parent
Inside Child

2. Using Super() : ฟังชันก์ Python super() ทำให้อ้างอิงถึงคลาสหลักได้ โดยฟังชันก์จะรีเทิร์น proxy object

ตัวอย่าง

# Python program to demonstrate 
# calling the parent's class method 
# inside the overridden method using 
# super() 
class Parent(): 
    
    def show(self): 
        print("Inside Parent") 
        
class Child(Parent): 
    
    def show(self): 
        
        # Calling the parent's class 
        # method 
        super().show() 
        print("Inside Child") 
        
# Driver's code 
obj = Child() 
obj.show() 

เอาท์พุต

Inside Parent
Inside Child

ตัวอย่างโค้ดเปรียบเทียบ

using System;  
public class Animal{  
    public virtual void eat(){  
        Console.WriteLine("Eating...");  
    }  
}  
public class Dog: Animal  
{  
    public override void eat()  
    {  
        Console.WriteLine("Eating bread...");  
    }  
}  
public class TestOverriding  
{  
    public static void Main()  
    {  
        Dog d = new Dog();  
        d.eat();  
    }  
} 

reference

C# method overriding and override https://www.geeksforgeeks.org/c-sharp-method-overriding/

C# virtual keywordhttps://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual

C# base Keyword https://www.javatpoint.com/c-sharp-base

java method overriding, กฎสำหรับ Java Method Overriding, Overriding and Constructor, Overriding and Abstract Method, Overriding and Synchronized/strictfp Method https://www.geeksforgeeks.org/overriding-in-java/

java Overriding and Exception-Handling https://www.javatpoint.com/exception-handling-with-method-overriding

Python Method Overriding, Calling the Parent’s method within the overridden method https://www.geeksforgeeks.org/method-overriding-in-python/

Python Method overriding with multiple and multilevel inheritance https://www.javatpoint.com/method-overriding-in-python

presentation

video

https://youtu.be/CGjiBvMc4mo

Last updated