hopsite.blogg.se

Java downcast
Java downcast








("The Measurable shape's area is " + area + " square " + units + ".") Public static void displayArea(Measurable shape, String units) Now, let’s define the following method whose parameter, shape, has Measurable as its data type: /** Displays the area of a Measurable object.

java downcast

A cast to Square would be required in both cases. And, as we have seen, you could not assign a Measurable type variable to one of the Square types. You can pass it as an argument whose data type is Square, but not Measurable. The data type of displaySide’s parameter, aSquare, is Square. ("The Square's side is " + side + " " + units + ".") Public static void displaySide(Square aSquare, String units) Now, consider the following method that we could add to the previous program: /** Displays the side of a Square object. The following program contains the previous statements so that you can verify their effect and experiment with them: Object instead of a Square object, you cannot cast box to Square. For example, if box actually references a Circle If, however, box does not reference a Square object, an exception will occur if you try to cast it to Square. The compiler will believe you, so the following statement will compile and execute correctly, as seen here: double boxAsSquareSide = boxAsSquare.getSide() // Legal due to previous cast For example, you could write this: Square boxAsSquare = (Square)box // I promise that box references an object that has Square methods. You can tell the compiler to assume that box will reference a Square object by casting box to Square. Thus, the following statement is illegal and would cause a syntax error: double boxSide = box.getSide() // ILLEGAL: getSide is not in Measurableīecause compilation occurs before execution, the compiler does not know that box will reference a Square object when this statement executes. However, Square also defines the getSide method which Measurable does not declare. GetArea, we can invoke this method in a statement such as: double boxArea = box.getArea() // Legal Since the Measurable interface declares the getArea method and the Square class implements

  • Conversion from an interface type to a class type requires an explicit cast to the class type.Īgain, consider the following statement: Measurable box = new Square(2.5).
  • java downcast

    Conversion from a class type to an interface type is implicit and legal.✏️ Note: Conversions between class types and interface types However, to subsequently assign box to a variable of type Square it will require a cast: Square boxAlias = (Square)box Of type Measurable without a cast: Measurable box = new Square(2.5)

    java downcast

    Because Square implements Measurable, we can assign a Square object to a variable










    Java downcast