this is the code i was looking at.Its about how to use JTextPane and related swing text Components along with actions and keymaps.

my question is that in this part

        textPane = new JTextPane();
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5, 5, 5, 5));
        StyledDocument styledDoc = textPane.getStyledDocument();
        if (styledDoc instanceof AbstractDocument) {
            doc = (AbstractDocument) styledDoc;
            // doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));// DocumentSizeFilter doesnt work , eclipse giving errors
        } else {
            System.err
                    .println("Text pane's document isn't an AbstractDocument!");
            System.exit(-1);
        }

in the lines doc = (AbstractDocument) styledDoc; , does doc and styledDoc point to the same location in the heap ? or does the casting create a new memory-space / object-instance pointed to by doc.

a related question that was going on in my head was that :
if styledDoc is an instanceof AbstractDocument , why do we need the cast ?

They both refer to the same object (address on the heap), but for compile-time checking the compiler knows that styledDoc must always refer to some kind of StyledDocument and doc must always refer to some kind of AbstractDocument. The cast is telling the compiler that you expect these types to be compatible in this particular piece of code.
Note that StyledDocument is an interface, with two standard classes that implement it, viz: DefaultStyledDocument and HTMLDocument. As it happens, both of those classes extend (directly or indirectly) AbstractDocument, so the cast will be OK, but in general, you cannot be sure that a class that implements StyledDocument will extend AbstractDocument, so the two types are quite diferent.

the cast will be OK, but in general, you cannot be sure that a class that implements StyledDocument will extend AbstractDocument

so i guess the instanceOf check was a best-practices example for code in general. thanks for the nice and simple explanation :)

another question i would like to ask is that the code also shows the use of the DefaultEditorKit for functions like undo etc.
taking undo as a reference , is there any performance benefits of say using the DefaultEditorKit over methods implemented using UndoManager with key-binding ?

so i guess the instanceOf check was a best-practices example for code in general

Yes - because if you get it wrong you get a horrible cast execption at run time, very messy.

Sorry, I don't have any useful info/experience comparing DefaultEditorKit vs UndoManager.
J

thanks again :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.