I've a question about inherited classes and List
types. Imagine that you've created a class called Polygon
with some methods (calculate perimeter, area, etc) and a class called Triangle
that extends Polygon
. At the same time, in your Main class, you've created a List
type that saves Polygon
objects. Everything belongs to the same package.
My doubt it's the next one: if I create an object from type Triangle
, can I save it into this last one List
?
Example:
Class Polygon
public class Polygon{
//All his methods
}
Class Triangle
public class Triangle extends Polygon{
//All his methods
}
Main Class
public static void main (String[] args){
List<Polygon> listPolygon = new ArrayList <Polygon> ();
Triangle example = new Triangle();
listPolygon.add(example);
}
Thank you a lot and sorry for my possible bad English. I'm practicing a lot right now.
I am not sure of your question.
If your question is can you do this:
List<Polygon> polygonList = new ArrayList<Polygon>();
Triangle triangle = new Triangle();
polygonList.add(triangle);
the answer is yes , because a Triangle
is a Polygon
.
If the question is, can you do this:
List<Triangle> triangleList = new ArrayList<Triangle>();
List<Polygon> polygonList = triangleList;
the answer is no , because a List<Triangle>
is not a List<Polygon>
. See this question for more details.
If you are using an IDE, such as eclipse or IntelliJ, you should quickly find out what you can or cannot do, as you get helpful error messages.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.