繼承是物件導向程式設計(OOP)的核心概念,它允許一個類別取得另一個類別的屬性(屬性和方法)。在Java中,繼承是使用extends關鍵字實現的,並表示「is-a」關係。本文透過一個實際例子解釋了Java中的繼承。
// Defining a class class Animal { // General attributes protected String colour; protected String breed; protected int age; // General methods public String sleep() { return "Both cats and dogs sleep"; } public String eat() { return "They also eat"; } // Constructor public Animal(String colour, String breed, int age) { this.colour = colour; this.breed = breed; this.age = age; } // Getters and setters public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } // Cat class inheriting from Animal class class Cat extends Animal { private String catName; public Cat(String colour, String breed, int age, String catName) { super(colour, breed, age); // Call the parent class constructor this.catName = catName; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public String catSound() { return "Cat meows!"; } } // Dog class inheriting from Animal class class Dog extends Animal { private String dogName; public Dog(String colour, String breed, int age) { super(colour, breed, age); } public String getDogName() { return dogName; } public void setDogName(String dogName) { this.dogName = dogName; } public String dogSound() { return "Dog barks!"; } } public class Demo { public static void main(String[] args) { Cat myCat = new Cat("Brown", "Persian", 2, "Tom"); Dog myDog = new Dog("Black", "Labrador", 3); // Display Cat details System.out.println("Cat's Name: " + myCat.getCatName()); System.out.println("Cat's Colour: " + myCat.getColour()); System.out.println("Cat's Breed: " + myCat.getBreed()); System.out.println("Cat's Age: " + myCat.getAge()); System.out.println("Cat Sound: " + myCat.catSound()); System.out.println("Cat Behavior: " + myCat.eat() + " and " + myCat.sleep()); // Display Dog details System.out.println("Dog's Colour: " + myDog.getColour()); System.out.println("Dog's Breed: " + myDog.getBreed()); System.out.println("Dog's Age: " + myDog.getAge()); System.out.println("Dog Sound: " + myDog.dogSound()); } }
Cat's Name: Tom Cat's Colour: Brown Cat's Breed: Persian Cat's Age: 2 Cat Sound: Cat meows! Cat Behavior: They also eat and Both cats and dogs sleep Dog's Colour: Black Dog's Breed: Labrador Dog's Age: 3 Dog Sound: Dog barks!
我的 GitHub
java 倉庫
以上是透過實例了解Java中的繼承的詳細內容。更多資訊請關注PHP中文網其他相關文章!