r/JavaProgramming • u/Few_Strain_8521 • 1d ago
I built a small Java program to practice inheritance — looking for feedback
I'm currently learning Java and recently practiced inheritance by creating a simple example with a Person parent class and Student child class.
I understand the basic concept, but I'm still trying to understand when inheritance is actually useful in a real project rather than just using it because the language allows it.
For people who use Java professionally, what are some situations where inheritance makes sense, and when would you choose composition instead?
I'm interested in understanding the reasoning behind the design choice, not just the syntax.
1
u/No_Assignment9285 1d ago
I'll give you an example in the world of web development. Suppose you want to create multiple DB tables that uses the columns updated at, created at, then create a super class and inherit that for the classes that creates the DB tables. Simple?
1
1
u/Ollidav 1d ago
Persona es una idea abstracta ya que podemos saber que hablamos de personas pero no podemos concretar que persona es ya que, aunque todas tienen atributos en común, unas pueden ser altas, calvas o con diferente color de piel u ojos. La idea de herencia sería que quiero trabajar con Persona que tiene unos atributos como altura, color de pelo, ojos y puede andar hacia delante o atrás, saltar, tumbarse, etc... pero durante el desarrollo voy a necesitar diferentes tipos de personas. Muchas de esas personas compartirán atributos como el de saltar, caminar o tumbarse pero tendrán un diferente color de pelo, altura, peso o velocidad al moverse.
1
u/MentalAnteater1286 19h ago
Inheritance makes sense when the child truly is a specialized version of the parent. composition is usually better when you just want to reuse behavior
1
u/Inevitable_Leg5543 16h ago
Inheritance makes sense when the child truly is a specialized version of the parent. composition is usually better when you just want to reuse behavior
2
u/Educational-Paper-75 1d ago
Use inheritance when the relationship is an IS A relationship and composition in a HAS A relationship. A car HAS an engine, a human IS a mammal IS an animal.