Numbers.add(3.14) // auto-boxing converts primitive to new Double(3.14)Here, as you can see, the Substitution Principle is applied for the reference type ( List) and object type ( ArrayList). Numbers.add(2016) // auto-boxing converts primitive to new Integer(2016) Java Generics with Subtyping and the Substitution PrincipleA list of Number can contain Integer and Double objects (two subtypes of Number), hence the following example: List numbers = new ArrayList() JPanel is a class in Swing, which has the add(Component) method, and JButton and JTextField are two subtypes of Component. Subtyping in method invocation: JPanel panel = new JPanel() This principle is then adopted in object-oriented programming languages.The Substitution Principle states that:Ī variable of a given type may be assigned a value of any subtype, and a method with a parameter of a given type may be invoked with an argument of any subtype of that type.Here’s a couple of examples in Java:- Subtyping in declarations: Number num = new Integer(2000) What is the Substitution Principle?The Substitution Principlewas developed in 1987 by Barbara Liskov - an American computer scientist (hence it is also called Liskov’s Substitution Principle). In Java, Sis a subtype of T if S extends or implements T.Subtyping is transitive, meaning that if R is a subtype of S, then R is also a subtype of T ( T is the super type of both Sand R).Here are some examples:Ģ. What is subtyping?Subtyping is a key feature of object-oriented programming languages such as Java. They are subtyping and the Substitution Principle. This article helps you understand a couple of important rules with regard to generics in Java.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |