Superclass reference to subclass object?

Give me a situation where we need to use a superclass reference for a subclass object in Java. Please give me a real-time example.

thank

+3
source share
10 answers

I know this is old, but it appeared in a project I was working on recently (only the junior developer is doing something unexpected - there was no real reason for this!), And I think some of the answers missed the point ..

This has nothing to do with normal polymorphism; I think the question relates to the case where the code looks like this:

class A {
    B b; //odd reference here..
}
class B extends A {
}

. , - , , , , Java, . Object.

, , Object String toString , String Object.

, , , , .

.

class A {
    B b;
    A(){
        b = new B();
    }
}
class B extends A {
}

- , , B , B ..

+5

... , ... , Interface, , ...

abstract class Shape {

    abstract double getArea();

}

class Rectangle extends Shape{
    double h, w;

    public Rectangle(double h, double w){

        this.h = h;
        this.w = w;
    }

    public double getArea(){
        return h*w;
    }
}

class Circle extends Shape{
    double radius;

    public Circle(double radius){
        this.radius = radius;
    }

    public double getArea(){
        return Math.PI * Math.sqrt(radius);
    }
}

class Triangle extends Shape{
    double b, h;

    public Triangle(double b, double h){
        this.b = b;
        this.h = h;
    }

    public double getArea(){
        return (b*h)/2;
    }


}

public class ShapeT{
    public static void main(String args[]){

    //USAGE
    //Without polymorphism
    Triangle t = new Triangle(3, 2);
    Circle c = new Circle(3);
    Rectangle r = new Rectangle(2,3);

    System.out.println(t.getArea());
    System.out.println(c.getArea());
    System.out.println(r.getArea());

    //USAGE with Polymorphism

    Shape s[] = new Shape[3];
    s[0] = new Triangle(3, 2);
    s[1] = new Circle(3);;
    s[2] = new Rectangle(2,3);

    for(Shape shape:s){
        System.out.println(shape.getArea());
    }

    }
}

, ... !

+2

. .

, ; .

, , .

+2
class Person
String hairColor = "default_noColor";
-----------------------------
class German extends Person
String hairColor = "brown";
-----------------------------
class Scandinavian extends Person
String hairColor = "red";
-----------------------------
public static void main(String args[]) {
    Person p = new Person();
    German g = new German();
    Scandinavian s = new Scandinavian();
    sysout p.hairColor // prints default_noColor
    if (cond1) {
        p = g;
    }
    sysout p.hairColor // prints brown
    else if (cond2) {
        p = s;
    }
    sysout p.hairColor // prints red
}

, , , () , . , .
,

+1

, , .

  public class Reference {


    public static void main(String args[]){
        A a = new B();
        //B b = new A(); // You can not do this, compilation error
        a.msg(); // calls the subclass method
        ((B)a).msg("Custom Message"); // You have to type cast to call this
        System.out.println(a.getClass());
        if(a instanceof B){//true
            System.out.println("a is instance of B");
        }
        if(a instanceof A){//true
            System.out.println("a is instance of A also");
        }


    }
}

class A{
    public void msg(){
        System.out.println("Message from A");
    }
}

class B extends A{
    public void msg(){//override
        System.out.println("Message from B");
    }
    public void msg(String msg){//overload
        System.out.println(msg);
    }

}
+1

java , , java , .

Rectangle, , - . Square Rectangle, Rectangle.

<head>
        <title>To Use Superclass Variables With Subclassed Objects</title>
    </head>
    <body>
        <h1>To Use Superclass Variables With Subclassed Objects</h1>

        <%!
            javax.servlet.jsp.JspWriter pw;
            class Rectangle
            {
                public void areaOfRectangle() throws java.io.IOException 
                {
                    pw.println("Starting...<br>");
                }
            }
            class Square extends Rectangle
            {
                public void area() throws java.io.IOException 
                {
                    pw.println("Creating...<br>");
                }
            }
            class Triangle extends Square
            {
                public void area() throws java.io.IOException 
                {
                    pw.println("Creating...<br>");
                }
            }
        %>     
        <%
            pw = out;     
            out.println();
            out.println("Creating an Area...<br>");
            Rectangle p = new Triangle();
            p.areaOfRectangle();
        %>
    </body>
</html> 
0

? - :

class Node {
   has 'next' => ( isa => 'Node' );
}

class TextNode extends Node {
   has 'text' => ( isa => 'Str' );
}

class ImageNode extends Node {
   has 'image' => ( isa => 'Image' );
}

:

TextNode->new( 
    text => 'Here is my cat:', 
    next => ImageNode->new(
        image => 'nibbler.jpg',
        next  => undef,
    ),
);

Node, TextNode ImageNode, , , Java:

 Node->new( next => TextNode->new ( ... ) )

Node ... .

, , , , .

0

: java.lang.reflect.Array:

Array Java.

  • getLength(Object array)
    • , int.
  • get(Object array, int index)
    • .
  • set(Object array, int index, Object value)
    • .

Object, . , : , .

0

, , (, singleton), ; .

, , . (, - , , , ...)

0

I think this can happen if the class and its subclass share a child parent relationship of some kind, and the child has a link to his parent, something like this

public interface Node
{   
    String getName();

    int getValue();

    Container getParentContainer();
}

public interface Container extends Node
{   
    Set<Node> getChildren();
}

I would be interested to see how this can be better designed to solve this problem.

0
source

Source: https://habr.com/ru/post/1738908/


All Articles