为什么我们使用继承,当我们可以创建另一个类的对象并使用它的方法和实例变量时? (反之亦然 - 为什么我们只能使用继承来创建另一个类的对象?)
这不是一个家庭作业问题。当我教导我们继承时,我向老师提出了这个问题,但他并不知道答案。我问我的学费老师,他甚至无法帮助我。我多次阅读教科书,在互联网上搜索一个简单的解释,但没有运气。请帮帮我。
答案 0 :(得分:5)
继承和组合都可以替代地用于代码重用能力。
为什么组合优先于继承? 最好使用组合而不是继承,因为它用于代码重用 - 能力的目的,而不需要担心变化的涓滴效应。因此,它提供了更松散的耦合,我们不必担心更改某些代码导致其他一些需要更改的相关代码。
例如: 考虑我们有以下类:
class Person
{
public String name;
public int age;
public Person(String name,int age)
{
this.name = name;
this.age = age;
}
}
class Student : Person
{
public String rollNumber;
public double cgpa;
public Student(String rollNumber,double cgpa,String name,int age):base(name,age)
{
this.rollNumber = rollNumber;
this.cgpa = cgpa;
}
}
//and the main which call these as
static void Main(string[] args)
{
Student student = new Student("Roll1234", 3.5, "John Doe", 32);
}
现在如果Person类要改变并且如下所示:
class Person
{
public String firstName;
public String lastName;
public int age;
public Person(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
如果不更改从Person类继承的所有类,在我们的类Student类中,则无法实现此更改。
现在考虑另一种情况,我们在下面的代码中使用了合成:
class Person
{
public String name;
public int age;
public Person(String name,int age)
{
this.name = name;
this.age = age;
}
}
class Student
{
public String rollNumber;
public double cgpa;
public Person person;
public Student(String rollNumber,double cgpa,Person person)
{
this.rollNumber = rollNumber;
this.cgpa = cgpa;
this.person = person;
}
}
//and the main
static void Main(string[] args)
{
Person person = new Person("John Doe", 32);
Student student = new Student("Roll1234", 3.5, person);
}
现在在这种情况下,如果我们要在Person类中进行如下更改:
class Person
{
public String firstName;
public String lastName;
public int age;
public Person(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
我们根本不需要更改学生课程。因此,组合使我们的设计在变化时更加灵活。
然而,经验法则表明,如果有一个"是"关系继承和去组成"有一个"关系。
但是请记住,如果要实现代码重用,组合将永远是一个更好的选择。