Java 程式實現多重繼承


在本文中,我們將瞭解如何實現多重繼承。 Java 不支援多重繼承。這意味著一個類不能擴充套件多個類,但是我們仍然可以使用 關鍵詞“extends” 實現這一結果。

實現多重繼承的演算法

Step 1 – START
Step 2 – Declare three classes namely Server, connection and my_test
Step 3 – Relate the classes with each other using 'extends' keyword
Step-4 – Call the objects of each class from a main function.
Step 5 – STOP

示例 1

class Server{
   void my_frontend(){
      System.out.println("Connection to frontend established successfully");}
   }
   class Java extends Server{
      void my_backend(){
         System.out.println("Connection to backend established successfully");
      }
   }
   class connection extends Java{
      void my_database(){
         System.out.println("Connection to database established successfully");
      }
   }
   public class my_test{
      public static void main(String args[]){
         connection my_connection=new connection();
         my_connection.my_database();
         my_connection.my_backend();
         my_connection.my_frontend();
   }
}

輸出

Connection to database established successfully
Connection to backend established successfully
Connection to frontend established successfully

示例 2

interface My_restaurents {
   void eat();
}
interface My_journey {
   void travel();
}
class Holiday implements My_restaurents, My_journey {
   public void eat() {
      System.out.println("I am trying this food");
   }
   public void travel() {
      System.out.println("I am trying this route");
   }
}
public class My_trip {
   public static void main(String args[]) {
      Holiday my_schedule = new Holiday();
      my_schedule.eat();
      my_schedule.travel();
   }
}

輸出

I am trying this food
I am trying this route

更新於: 2024 年 6 月 21 日

1.5 萬+ 瀏覽量

開始你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.