Object-oriented programming languages, for example. java, C #, ... support for object types. For example, this is perfectly true in java:
URL url = new URL("url"); URLConnection conn = url.openConnection(); if( !conn instanceof HttpURLConnection ) throw new Exception("not http request"); HttpURLConnection con = (HttpURLConnection) conn;
Or another basic example that I tried:
public class Base { public void base(){} } public class Derived extends Base { public void derived(){} } Base b = new Derived(); b.base();
A derived class has all the methods of the base class, plus more. There is no reason why you cannot create a base class by calling the constructor of the derived class.
I also stumbled upon this link http://www.volantec.biz/castingObjects.htm , which explains how object modeling works. Still good.
But why is the HttpURLConnection con = new HttpURLConnection("url address") not used in the first example (I know HttpURLConnection is an abstract class). It just seems more understandable, simpler. On the other hand, when dealing with interfaces , casting objects will be useful . Another example is the List<Object> list, which I sometimes see in some classes. This means that you can save all possible classes in this list. After that, you can simply give it to the original if you know what type it is. It would not be clearer to save only certain classes to list, i.e. List<String> , List<MyClass> . Does List<Object> good design practice in general?
source share