+ 1

Why use inheritance if we can access other class's methods and variables by creating object of that class in required class?

2nd Jan 2017, 11:28 AM
alonewolf
alonewolf - avatar
4 odpowiedzi
+ 3
With inheritance, we can create subclasses. It allows us to use both superclass(base class) and subclasses(derived class) methods. For example; we have Person class that have printName, printAge and printAdress methods. If we create a subclass named Student from Person class (Student extends Person) then add printSchoolNumber and printGpa methods to Student class, it will have all of five methods. If we don't inherit Student class from Person class, we need to rewrite more methods for printing name, age, adress etc.
2nd Jan 2017, 3:04 PM
Bekir Uzun
Bekir Uzun - avatar
+ 3
In my example Student class have only schoolNumber and Gpa fields; printSchoolNumber and printGpa methods declared but it have Person class fields and methods too. Even though I didn't rewriten Persons class methods and fields, I can reach them from main function. If you dont inherit from Person class, you cant reach Person class fields and methods from main with Student object. So you need to rewrite printName method in Student class.
2nd Jan 2017, 4:38 PM
Bekir Uzun
Bekir Uzun - avatar
+ 1
@Bekir but we can access the methods of person class by creating objects of person class in student class, so where does inheritance is helping?
2nd Jan 2017, 4:21 PM
alonewolf
alonewolf - avatar
0
@Bekir but i will declare object of person class in main method of student class and hence I can access methods of persons. Correct me if I'm wrong!!:)
2nd Jan 2017, 5:35 PM
alonewolf
alonewolf - avatar