面向对象继承的代码有哪些

面向对象继承在许多编程语言中都是一种重要的技术,可以用于实现代码重用和扩展。以下是不同语言中面向对象继承的代码示例:

Java:

// Animal类作为父类,定义了基本属性和方法
public class Animal {
    private String name;
    private int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping.");
    }
}

// Dog类继承自Animal类,并添加了新的属性和方法
public class Dog extends Animal {
    private String breed;

    public Dog(String name, int age, String breed) {
        super(name, age);
        this.breed = breed;
    }

    public void bark() {
        System.out.println(name + " is barking.");
    }
}

Python:

# Animal类作为父类,定义了基本属性和方法
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def eat(self):
        print(self.name + " is eating.")
    
    def sleep(self):
        print(self.name + " is sleeping.")

# Dog类继承自Animal类,并添加了新的属性和方法
class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)
        self.breed = breed
    
    def bark(self):
        print(self.name + " is barking.")

c++:

// Animal类作为父类,定义了基本属性和方法
class Animal {
private:
    std::string name;
    int age;
public:
    Animal(std::string name, int age) {
        this->name = name;
        this->age = age;
    }
    
    void eat() {
        std::cout << name << " is eating." << std::endl;
    }
    
    void sleep() {
        std::cout << name << " is sleeping." << std::endl;
    }
};

// Dog类继承自Animal类,并添加了新的属性和方法
class Dog : public Animal {
private:
    std::string breed;
public:
    Dog(std::string name, int age, std::string breed) : Animal(name, age) {
        this->breed = breed;
    }
    
    void bark() {
        std::cout << name << " is barking." << std::endl;
    }
};

以上是三种不同语言中面向对象继承的代码示例。在这些示例中,父类通常包含了一些基本属性和方法,子类通过继承父类来获取这些基本功能,并且可以添加自己的属性和方法以实现扩展和定制化。