+ 1

Is writing subclass inside the parent class same as writing subclass and referencing it to parent class using extends ?

Is writing the subclass inside the parent class, the same as referencing the parent class using 'extends' while declaring the subclass ? For example class Animal{ boolean Is_Alive; class dog{ private int legs = 4; } } Is the above code same as writing class Animal{ boolean Is_Alive; } class Dog extends Animal{ private int leg = 4 } Thank you

15th Aug 2020, 8:00 AM
GGWellPlayed
GGWellPlayed - avatar
2 Respuestas
+ 1
If you define a subclass in a class this will be constructed with: new Class.Subclass(); If you define a class which extends a class It isn't a member of that class. So you can construct that class only with the name: new MyInheritedClass() ;
15th Aug 2020, 9:57 AM
S-Coder
S-Coder - avatar
+ 2
subclass always refers to the concept of inheritance, so you copy (and modify) the design of an existing class outside it, with the extends keyword. When you create a class inside another class, it is called "nested class". The nested class can be static, or nonstatic "inner classes" (as one that can be instantiated). This is very different from a subclass. Some design patterns, like the Singleton or Builder pattern, can be implemented with static inner classes. More reading: https://dzone.com/articles/what-are-nested-classes-and https://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html https://www.baeldung.com/creational-design-patterns
15th Aug 2020, 10:58 AM
Tibor Santa
Tibor Santa - avatar