When extending another class...?

I have made a BinaryTree class, tested it and everything and it all works.
Now, I have just made an AVLTree class. So, I want all the methods in the BinaryTree class to be the same as in the AVL class except the add method which I wanted to override.
So, I made the BinaryTree class abstract, and then extended the BinaryTree class in the AVL class.
So I thought that by doing this all I had to do was put in the add method and change the code and then I could use all the methods in the BinaryTree class.
Well it seems that I can, except that none of it works correctly because of private attributes. For example, my size doesn't update in my new add method and I can't figure out why. I have a private int size in both classes but it doesn't work. Not only that but my root node isn't working either.
I'll post some code here and hopefully someone knows what I'm doing wrong.
package avlTree;
* @author 383259
public class AVLTree extends BinaryTree
     private int size;
     private BSTNode root;
     private String side;
     public AVLTree()
          super();
      * @param element
     public AVLTree(Comparable element)
          super(element);
      * @param element
      * @param left
      * @param right
     public AVLTree(Comparable element, BSTNode left, BSTNode right)
          super(element, left, right);
      * @param element
      * @param left
      * @param right
     public AVLTree(Comparable element, BinaryTree left, BinaryTree right)
          super(element, left, right);
private BSTNode addToTree(Comparable o)
          try
               boolean status = false;
               if(isEmpty())
                    System.out.println("yes");
                    status = true;
                    root = new BSTNode(o);
                    size++;
                    setRoot(root);
                    return root;
               else
                    System.out.println("yes");
                    BSTNode currNode = root;
                    BSTNode newNode = new BSTNode(o);
                    while (status == false)
                         if(newNode.compareTo(currNode.getElement()) == 1)
                              if (currNode.getRight() == null)
                                   currNode.setRight(newNode);
                                   newNode.setParent(currNode);
                                   size++;
                                   side = "right";
                                   status = true;
                                   return newNode;
                              else
                                   currNode = currNode.getRight();
                         else if(newNode.compareTo(currNode.getElement()) == -1)
                              if (currNode.getLeft() == null)
                                   currNode.setLeft(newNode);
                                   newNode.setParent(currNode);
                                   size++;
                                   side = "left";
                                   status = true;
                                   return newNode;
                              else
                                   currNode = currNode.getLeft();
                         else
                              status = true;
                              return null;
                    return null;
               catch (ClassCastException cce)
                    return null;
               catch (NullPointerException npe)
                    return null;
               catch (IllegalArgumentException iae)
                    return null;
     }That private, addToTree method is actually the same as the add method in the binary tree, but is only a small part of the add method in the AVLTree. Anyway, my private root node attribute and size attribute aren't updating for some reason or another, and I cannot figure out why.

So, I made the BinaryTree class abstract,And you did that why exactly?
So I thought that by doing this all I had to do was
put in the add method and change the code and then I
could use all the methods in the BinaryTree class. Which is correct. Minus the private stuff, as you found out. That's what private means, after all.
Well it seems that I can, except that none of it
works correctly because of private attributes. For
example, my size doesn't update in my new add method
and I can't figure out why. I have a private int size
in both classes but it doesn't work. Not only that
but my root node isn't working either.I guess it doesn't work because you now have two size variables and constantly use the wrong one. Make size protected, or better, provide a protected setter for the size. Do the same for other private attributes you need to access.

Similar Messages

  • Error 1119 when class extends another class that extends movieclip

    hiya
    i came across this problem and i have no clue why it's happening. basically, consider 2 nested movieclips on the stage, something like stage -> main -> filler.  both movieclips have instance names (main and filler).
    in the library, i set main to export for actionscript, using class A:
    package {
        import flash.display.MovieClip;
        public class A extends MovieClip {     
            public function A ():void {
                trace ('construct A');
                trace (this.filler); // should trace [movieclip] etc
    it works fine. now i change it's export settings to use class B, that extends A, and it breaks:
    package {
        import flash.display.MovieClip;
        public class B extends A {
            public function B ():void {
                trace ('construct B');
    this throws an error 1119: Access of possibly undefined property filler through a reference with static type A.
    can anyone give me a hint on that, as it works with class A, but not B extending A? i understand it was meant to work?
    many thanks

    afaik, if you dont declare super(), flash will make a call for you (but best practice is to call it always).
    but i found the "solution" in another forum.
    it seems that flash implicitly generates variables if you have instance names/symbols on the stage. there is an option to disable that under publish settings -> Actionscript version -> Settings -> automatically declare stage instances. by disabling that, we were able to declare public var filler:MovieClip; on class A, and that worked.
    although, that solution doesnt look attractive to me. the other solution posted on another forum was to make calls to this ["filler"] instead of this.filler. that seems to work fine. i guess it has to do with the automatic variable generated thing.. who knows?
    i hope that helps someone else too

  • Calling a private function when inside another class?

    Can't help it but im curious how classes seem to be able to
    call private functions inside other classes. I'm mainly thinking
    about the addEventListener() here. When adding a listening function
    to a class, that function can be private, and yet it seems to be
    called magically somehow. Or maybe its all internal? I dunno.
    Anyone? :D

    Hi Kenchu1,
    You can grab a copy of the open source API here:
    http://www.baynewmedia.com/download/BNMAPI10.zip
    (feel free to drop by
    the main site for documentation as well :) ). The main class
    is the
    Events class, "broadcast" method. This method broadcasts
    events in a
    decoupled fashion, meaning that listeners can listen to
    messages that
    aren't bound to a specific sender. The AS3 version works in
    much the
    same way except that I still haven't fully fleshed out the
    cross-SWF
    communication that this version can do (broadcast across all
    movies on
    the same computer using LocalConnection).
    Basically, the broadcaster works like this:
    1. Add event listener and bind to function A (called from
    within the
    class so the reference is available)
    2. Event listener pushes this into the listener array. It was
    provided
    by the class so the reference is valid and is now a part of
    the events
    class as well.
    3. Broadcast runs through all associated events when it comes
    time to
    broadcast and calls the function by using the array
    reference:
    this.listeners[message].call(classInstance,someParameter);
    In other words, the class that adds the listener "allows"
    the event
    broadcaster to use the reference because it passes it out.
    You can do
    the same thing by calling:
    someOtherclass.functionRef=this.privateFunction
    someOtherClass is the class that will store the private
    reference,
    functionRef is some variable to hold the reference, and
    privateFunction
    is the private function. Then, in someOtherClass, you can
    call:
    this.fuctionRef(someParameter);
    Hope this helps.
    Patrick
    Kenchu1 wrote:
    > Patrick B,
    > exactly! Something like that is what im looking for. I
    have my own rather
    > simple system right now with listeners and classes
    calling these, but since i
    > dont know how to call a private function, i had to make
    all the listening
    > classes functions public - something id rather avoid.
    Exactly how did your
    > event broadcasting system work? Oh, and we're talking
    AS3 btw.
    >
    > How do i call a function via a reference? (to the
    function? To what?)
    >
    http://www.baynewmedia.com
    Faster, easier, better...ActionScript development taken to
    new heights.
    Download the BNMAPI today. You'll wonder how you ever did
    without it!
    Available for ActionScript 2.0/3.0.

  • LoadClass    (error loading a class which extends other class  at run-time)

    Hey!
    I'm using the Reflection API
    I load a class called 'SubClass' which exists in a directory called 'subdir' at run-time from my program
    CustomClassLoader loader = new CustomClassLoader();
    Class classRef = loader.loadClass("SubClass");
    class CustomClassLoader extends ClassLoader. I have defined 'findClass(String className)' method in CustomClassLoader.
    This is what 'findClass(String className)' returns:
    defineClass (className,byteArray,0,byteArray.length);
    'byteArray' is of type byte[] and has the contents of subdir/SubClass.
    the problem:
    The program runs fine if SubClass does not extend any class.
    If however, SubClass extends another class, the program throws a NoClassDefFoundError. How is it conceptually different?
    Help appreciated in Advance..
    Thanks!

    Because i'm a newbie to the Reflection thing, i'm notI don't see reflection anywhere. All I see is class loading.
    sure what role does the superclass play when i'm
    trying to load the derived class and how to get away
    with the errorWell... hint: all the superclass's stuff is not copied into the subclass.
    I am quite sure it fails to load the superclass because of classpath issues.

  • AS3.0: How to extend a class that extends MovieClip

    When I try to set the base class of a library symbol to a
    class that doesn't DIRECTLY extend MovieClip, but instead extends
    another class that DOES extend MovieClip, it's disallowed, saying,
    "The class 'Whatever' must subclass 'flash.display.MovieClip' since
    it is linked..."
    Is this just a validation bug in the property windows, only
    checking one class deep into the inheritance hierarchy? Because the
    specified class does extend MovieClip, just two levels in instead
    of one. Is there a fix for this? Or must library symbols always
    directly extend MovieClip? If so, why?

    Which classes from flash.display have you imported. Just
    because a class extends another doesn't mean that it inherits all
    of its properties. Saying a class extends sprite doesn't give you
    access to all of it's properties, members and display unless you
    first import flash.display.* or flash.display.Sprite. If you aren't
    already importing flash.display.*, try importing
    flash.display.MovieClip and see what happens...

  • Package.Class extends Package.Class ??

    Is there any way I can make a class in a package extend another class in the same package://---- File: JrcCode1.java
    package jrc;
    public class JrcCode1 {
      public JrcCode1() {
        System.out.println("JrcCode1");
    //---- File: JrcCode2.java
    package jrc;
    public class JrcCode2 extends JrcCode1 {     //cannot resolve symbol, class JrcCode1
      public JrcCode2() {
        super();
        System.out.println("JrcCode2");
    }Thanks,
    James

    The current directory is not automatically in the classpath.
    You have to set it up that way. That may be your problemI have tried doing this, and it's still the same! The first code compiles but the second code fails:
    javac -sourcepath . -classpath . JrcCode1.java
    javac -sourcepath . -classpath . JrcCode2.java
    Try extending jrc.JrcCode1. It might work, but i didnt test it outI have tried this, and it still fails:
    JrcCode2.java:3: cannot resolve symbol
    symbol : class JrcCode1
    location: package jrc
    public class JrcCode2 extends jrc.JrcCode1 {
    Any other ideas?
    Thanks alot!
    James

  • Extending a class (newbie)

    I'm very new to Java. I'm making use of custom web classes from a proprietary application.
    I want to write my own class by extending another class. My class need to do exactly what the super class does. The super class extends another class.
    Here is how it looks,
    MY CLASS:
    public RmCopyCommand extends DwCopyCommand
    THE SUPER CLASS:
    public DwCopyCommand extends DwDocbaseCommand
    The super class, DwCopyCommand, has four methods defined (plus many inherited). To make my class, RmCopyCommand, mimic the super class, I did the following:
    1. I made a constructor
    RmCopyCommand()
                   super();
    2. I duplicated the methods
    public boolean hasTransaction()
                   return super.hasTransaction();
    I did the above to all four methods defined in the super class. I also used TRY...CATCH blocks where necessary. The source compiled.
    Off course, this doesn't work. I got a nullPointerException error. What I want to do is use the exact functionality of DwCommand, but write another method that makes a call to an inherited method.
    Could anyone tell me what I might be doing wrong?
    I hope I included enough details. If you need further details, let me know.
    Thanks,
    Moshe

    Lets go through this point by point:
    I'm very new to Java. I'm making use of custom web
    classes from a proprietary application.
    I want to write my own class by extending another
    class. My class need to do exactly what the super
    class does. The super class extends another class.Does you class really need to do exactly what the super class does? If the super class has everything you need why are you subclassing it.
    Here is how it looks,
    MY CLASS:
    public RmCopyCommand extends DwCopyCommandThe above statement is all you need followed by {} according to your description.
    THE SUPER CLASS:
    public DwCopyCommand extends DwDocbaseCommand
    The super class, DwCopyCommand, has four methods
    defined (plus many inherited). To make my class,
    RmCopyCommand, mimic the super class, I did the
    following:
    1. I made a constructor
    RmCopyCommand()
    super();
    }You only need to do this for constructors with arguments. If you don't create a default constructor, one is created for you. Also if you don't call super() in your constructor it will automatically before anything else is executed.
    2. I duplicated the methods
    public boolean hasTransaction()
    return super.hasTransaction();
    }This is unneccesary. By subclassing a class all its public and protected members are part of the sub class.
    I did the above to all four methods defined in the
    super class. I also used TRY...CATCH blocks where
    necessary. The source compiled.
    Off course, this doesn't work. I got a
    nullPointerException error. What I want to do is use
    the exact functionality of DwCommand, but write
    another method that makes a call to an inherited
    method.Nothing that you have stated here would cause that.
    Could anyone tell me what I might be doing wrong?
    I hope I included enough details. If you need further
    details, let me know.
    Thanks,
    Moshe

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

  • Can I invoke a class that extends JAppl from another class extends JAppl

    Can I invoke a class that extends JApplet from another class that extends JApplet. I need to invoke an applet then select an action which opens another applet. Thanks in advance.

    Nobody is able to solve this problem, i cant even
    think this things. i have hope so plz try and get
    result and help.Did you understand what Sharad has said???
    Yep, you can forward to specific error page from servlet when even error occured in JSP. In order to achieve you have to open jsp file from servlet say example by using reqdisp.forward.
    handle exception in the part where you are forwarding. And forward to the specific error page inside catch block.

  • Can't add list element when calling a method from another class

    I am trying to call a method in another class, which contains code listmodel.addElement("text"); to add an element into a list component made in that class.
    I've put in System.out.println("passed"); in the method just to make sure if the method was being called properly and it displays normally.
    I can change variables in the other class by calling the method with no problem. The only thing I can't do is get listmodel.addElement("text"); to add a new element in the list component by doing it this way.
    I've called that method within it's class and it added the element with no problem. Does Java have limitations about what kind of code it can run from other classes? And if that's the case I'd really like to know just why.

    There were no errors, just the element doesnt get added to the list by doing it this way
    class showpanel extends JPanel implements ActionListener, MouseMotionListener {
           framepanel fp = new framepanel();
           --omitted--
         public void actionPerformed(ActionEvent e){
                  if(e.getSource() == button1){
                       fp.addLayer();
    /*is in a different class file*/
    class framepanel extends JPanel implements ActionListener{
            --omitted--
         public void addLayer(){
              listmodel.addElement("Layer"+numLayer);
              numLayer++;
    }

  • Can an abstract class extend another abstract class?

    Is it possible for an abstract class to extend another abstract class?
    Say
    public abstract class AComponent extends JComponent {
    Thanks.

    Yes

  • [svn:bz-trunk] 21285: Need to change _parent, privateCall and instance properties from private to protected in order to extend this class for another project

    Revision: 21285
    Revision: 21285
    Author:   [email protected]
    Date:     2011-05-20 07:53:23 -0700 (Fri, 20 May 2011)
    Log Message:
    Need to change _parent, privateCall and instance properties from private to protected in order to extend this class for another project
    Modified Paths:
        blazeds/trunk/apps/ds-console/console/ConsoleManager.as

    Revision: 21285
    Revision: 21285
    Author:   [email protected]
    Date:     2011-05-20 07:53:23 -0700 (Fri, 20 May 2011)
    Log Message:
    Need to change _parent, privateCall and instance properties from private to protected in order to extend this class for another project
    Modified Paths:
        blazeds/trunk/apps/ds-console/console/ConsoleManager.as

  • How do you call a method from  another class without extending as a parent?

    How do you call a method from another class without extending it as a parent? Is this possible?

    Why don't you just create an instance of the class?
    Car c = new Car();
    c.drive("fast");The drive method is in the car class, but as long as the method is public, you can use it anywhere.
    Is that what you were asking or am I totally misunderstanding your question?
    Jen

  • NoMatchingActionMethodException error when extending class

    I have a base class (BaseProcess) that extends the PageFlowController. This class has an instance of a form:
    ,FSFormBean. I also have an action method that uses this form:
    * @jpf:action
    * @jpf:forward name="success" path="../hub/HubController.jpf"
    public Forward submitNext(FSFormBean form){
    return new Forward("success");
    When I extend this class
    public class TestController extends BaseProcess
    and a JSP calls the action "submitNext", I get the following error:
    No Matching Action Method Exception. I noticed that the form (FSFormBean) is empty when this is called from the parents class. Can anyone tell me why? Is it because of the notations? There are several action methods that are used throughout my class and I trying to simply my code, how can I make this to work?
    Thanks,
    Marcelo

    Check the build directory - do a clean build - or delete following folder in your webapp directory
    build/netui/weboutput/_pageflow

Maybe you are looking for

  • Check for Duplicates

    Hi folks.  Any chance for some help with formulas on this one? I have a column of numbers.  I want to set a calculation in another test column, to see if there are any duplicates.  Column C:  The numbers to test Column J:  The test column So for J: =

  • WLS 8.1.2 : unsupported encoding: 'UTF-8, UTF-16'

    Hello, We are porting a web service from WLS 7.0.4 to WLS 8.1.2.0. It is a stateless session bean, we use "servicegen" to generate the WS deployment descriptor and the client is PocketSoap 1.5 This web service worked fine with WLS 7.0.4, but with WLS

  • T-40 USB Port

    Can I replace USB ports on my T 40 ,model 2373? . When I plug in any device(,memory stick,GPS receiver etc.) getting msg' Windows doesn't recognize this device.This is happening when device is plug in before boot up. But if laptop is already running

  • My ipod wont install apps

    my ipod wont install apps from yesterday afternoon (15,8,2011) please help me i havent done anything to my ipod lately i was trying to install commodore 64 on my ipod and it wouldnt install. already restarted and synced it 4.2.1

  • Nokia 5140 and iSync

    I just bought a Nokia 5140. It does not have bluetooth. I can get a USB data cable to connect the phone to the computer, but the Nokia software is Windows only. Has anyone tried connecting this Nokia phone (or any other model) with a cable? Will iSyn