tags:

views:

918

answers:

7

Give me a situation where we need to use the super class reference to a subclass object in Java.Please give me a real time example.

Thx

A: 

One of the strong features of java is that it is follows a OOPs concept, and one of the feature of OOP in java is that, we can assign a subclass object or variable to the variable of the superclass type.

In this example we have a class named Rectangle which is the superclass of class Square, and Square is a superclass of Triangle. We can assign the object references of class Square to the variable of Rectangle, as well as the object references of class 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> 
giri
thx Giri, But here I need the reason for the need.Please explain the code ?
JavaUser
Why in earth are you abusing JSP for this? Talking about OOP..
BalusC
How do we say Square is a super class of Triangle ?
JavaUser
And since when does Square extend a Rectangle, or a Triangle extend Square..? A square is just a rectangle with artificial data entry / modification constraints (not sufficient to create a new subclass), and triangle isn't even close to square. If you wanted different methods of drawing shapes and getting their properties, this would be better supported by the interface pattern.
Chris Dennett
Oh God, this example ....
ultrajohn
Truly appalling. Downvoted.
EJP
A: 

Uh, any time? If you have something like a polymorphic linked list:

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

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

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

Then you can do:

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

Your specific situation involves Node holding a reference to TextNode or ImageNode, which is probably fine in Java:

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

Though I would make Node a role in languages with that feature... the idea is largely the same.

The Liskov substitution principle states that subclasses should behave exactly like their superclasses, so you can substitute a subclass anywhere the superclass is used.

jrockway
"Node->new( next => TextNode->new ( ... ) )" ... that ain't Java!
TofuBeer
+1  A: 

To Take Full Advantage of polymorphism...You have to understand polymorphism fully for you to really appreciate this... You can actually achieve the same behavior using an Interface as appropriate, so they say...

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());
    }

    }
}

I hope I'm not wrong on this... just a thought!

ultrajohn
A: 

Here's an important and most instructive example: java.lang.reflect.Array:

The Array class provides static methods to dynamically create and access Java arrays.

  • getLength(Object array)
    • Returns the length of the specified array object, as an int.
  • get(Object array, int index)
    • Returns the value of the indexed component in the specified array object.
  • set(Object array, int index, Object value)
    • Sets the value of the indexed component of the specified array object to the specified new value.

Arrays are passed around as Object, which is the superclass of all array types. It's necessary because we're doing reflection: we don't always know what the array type will be at compile time.

polygenelubricants
How is this an example of the original question?
EJP
`java.lang.reflect.Array` is "a situation where we need to use the super class reference " (`Object`) "to a subclass object" (whether it be an `int[]`, `String[]`, `Foo[][]`, `Bar[][][]`, etc). It's a "real time example" (whatever that means) of where this is pretty much necessary. This is **as good of an example as any**! I strongly object to your downvote.
polygenelubricants
+1  A: 

That question doesn't seem quite right ... putting an explicit reference to a child-class in the parent-class seems like an intent to break the hierarchy and the library.

As soon as the parent-class starts to carry a reference to the child-class, the parent-class is dependant upon knowing it's descendants; that is bad.

Unless the question was misquoted here, I'd say your interviewer was talking through his hat.

Everyone
A: 

It's really rather odd because the type of situation where it might be useful (supplying a custom implementation of a singleton object for instance) has better alternatives to that; in particular the service loader mechanism.

And outside the world of globals in disguise you do tend to run into issues with circular references. (Consider that the super reference within your sub-class field points to the enclosing super instance which in turn is a reference from within the sub-class ...)

A: 

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 //now, if germans start having black hair, i recompile class German and the main() is totally agnostic of how the German has changed.The main method continues to work as if nothing ever happened and prints black. Kindly excuse miminmal grammar and syntax

seb