"Super" in inheritance

I don't really understand the concept of using super to access the constructor of the super class...
for example
when a code is called:
public Person(string name. String surname)
super(name, surname)
Does this not construct objects with the instance variables of the super class? This only works if the instance variables of the super class are defined "public".
So would it be an imporvement in design to declare instance variables private in the super class and then use a new set of instance variables that overshadows the instance variables of the super class? As a result of this, the instance variables of classes are private which is preferred... So then whats the use of the super( .... ) keyword?
I think i'm confusing myself!!
Thanks for your help in advance

Hi, thanks for your reply,
Doesn't the child class also inherit instance variables of the super class only if its is declared public? So why shuldn't we make use of it?
Just say you had the following super class
public class Animal
    public String name;
    public int numOfLegs;
    public boolean cannibal;
    puiblic Animal(String name, int numOfLegs, boolean cannibal)
        this.name = name;
        this.numOfLegs = numOfLegs;
        this.cannibal = cannibal;
    // Methods ...
}Then you have a subclass ythat you want to inherit methods and its behaviour.... so
public class Sheep
    //No need to define instance variables such as name ....
    // Instance variables of the sheep class
    private int woolThickness;
    private boolean vaccinated;
    public Sheep(String name, int numOfLegs, boolean cannibal)
        super(name, numOfLegs, cannibal)
        woolThickness = 0;
        vaccinated = false;
    // Methods
}so when a new object of type sheep is created and the
" super(name, numOfLegs, cannibal)" is called, doesn't it initialise these variables given in the constructor with the constructor of the superclass?

Similar Messages

  • ReadString problem!! could anyone help me take a look

    hi... i am doing a music Cd list program. there are two operation i need to do 1) insertion and 2) deletion. i have implemented my own sortList to do it... i work fine when i do the insertion to the list but it can`t perform well on deletion.. However, i am sure that my list deletion algoritm is totally correct... i perform two test as following to ensure my deletion is correct..but i think the problem is on my readString fucntoon ...could anyone help me take a look!!
    public class SortedListTesting
         SortedList musicCdList = new SortedList();
         ReadOperation theRo = new ReadOperation();
         //ErrorCheckingOperation theEco = new ErrorCheckingOperation();
         MusicCd temp;
         public void insertCdWithReadStringFunction()
              String musicCdsTitle;
              //try to prompt the user `s cd `s title for insertion to our List
              musicCdsTitle = theRo.readString("Please enter your CD`s title : ");
              musicCdList.insert(new MusicCd(musicCdsTitle));
              System.out.println("Number of items in the list: "
                                         + musicCdList.getNumberOfItems() + "\n" + musicCdList.toString() );
         public void deleteCdWithReadStringFunction()
              try
                   //try to prompt the user `s delected cd `s title
                   String keyword = theRo.readString("Please enter CD `s title to be delected from SMOA : ") ;
                   // System.out.println("The CD that you just deleted is " + keyword);
                   temp = musicCdList.delete(keyword);
                   System.out.println("Number of items in the list: "
                                  + musicCdList.getNumberOfItems() + "\n" + temp );
              catch ( InvalidDataException errorMsg )
                   System.out.println( errorMsg.getMessage() + "\n" );
                   System.out.println("Now, We have " + musicCdList.getNumberOfItems() + " items in the list, and the items as following  :\n" + musicCdList.toString() );
         public void insertCd()
              String musicCdsTitle;
              //try to input the string directly to our list
              musicCdsTitle = "ann";//theRo.readString("Please enter your CD`s title : ");
              musicCdList.insert(new MusicCd(musicCdsTitle));
              System.out.println("Now, the number of items in the list: "
                               + musicCdList.getNumberOfItems() + "\n" + musicCdList.toString() );
         public void deleteCd()
                            try
                              //try to input the String directly
                              String keyword = "ann"; //theRo.readString("Please enter CD `s title to be delected from SMOA : ") ;
                              System.out.println("The CD that you just deleted is " + keyword);
                              temp = musicCdList.delete(keyword);
                                 //System.out.println("Number of items in the list: "
                                 //                     + musicCdList.getNumberOfItems() + "\n" + temp );
                         catch ( InvalidDataException errorMsg )
                              System.out.println( errorMsg.getMessage() + "\n" );
                        System.out.println("Now, We have " + musicCdList.getNumberOfItems() + " items in the list, and the items as following  :\n" + musicCdList.toString() );
         public static void main(String[] args)
              SortedListTesting st = new SortedListTesting();
              //These two testing i am trying to show that my list is working fine for inseting and deleting
              //i try to input the cd `s title name " ivan " by my readString function, it work fine for insertion
              //but it is fail in delete fuction..it shows that "ivan not found: cannot be deleted" ...At first,
              //i think it is my delete function problem..but it is not my delete function problem...cos it work fine if
              //input the string directly from the function...i think the issues works on my readString fucntion
              //i try a milllion of time but i still got the same problem ...pls help....
              System.out.println("\t...Testing for input from readString fuction...\t");
              st.insertCdWithReadStringFunction();
              st.deleteCdWithReadStringFunction();
              //it work fine for input the string directly in the function, it show as following...
              System.out.println("\t...Testing for input the string directly ...\t");
              st.insertCd();
              st.deleteCd();
    javac SortedListTesting.java
    Exit code: 0
    java SortedListTesting     ...Testing for input from readString fuction...     
    Please enter your CD`s title : ivan   <<-inserting the cd`s title to our list
    Number of items in the list: 1     <<- sucessfully insert to our list
    Title: ivan 
    Please enter CD `s title to be delected from SMOA : ivan  <<- try to delete from our list, i type "ivan" here
    ivan not found: cannot be deleted    <<- problem occur , it should be fine in there
    Now, We have 1 items in the list, and the items as following  :
    Title: ivan         <<- it should not be shown
         ...Testing for input the string directly ...     
    Now, the number of items in the list: 2
    Title: ann   <<- i pass "ann" String directly to insertion function
    Title: ivan   <<- it is the left over from the preivous process
    The CD that you just deleted is ann   <<- i pass " ann" String directly to my deletion
    Now, We have 1 items in the list, and the items as following  : <<- it successfully delete .... it prove that my deletion function is working properly....i think it is on readString problem..
    Title: ivan
    Exit code: 0*/
    //it seems that the readString function read the string
    //at the first time does not match the second time
    //reading, it makes it can`t find the stuff from the list ..
    import java.util.*;
    public class ReadOperation{
         //pls help check here....thx
         public String readString(String userInstruction)
              String aString = null;
              try
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aString = scan.nextLine();
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aString;
         public char readTheFirstChar(String userInstruction)
              char aChar = ' ';
              String strSelection = null;
              try
                   //char charSelection;
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   strSelection = scan.next();
                   aChar =  strSelection.charAt(0);
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aChar;
         public int readInt(String userInstruction) {
              int aInt = 0;
              try {
                   Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aInt = scan.nextInt();
              } catch (InputMismatchException e) {
                   System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
              } catch (NoSuchElementException e) {
                   System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
              } catch (IllegalStateException e) {
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aInt;
    public class SortedList extends ShellSortedList implements SortedListInterface<MusicCd>
         public SortedList()
              super();
         public void insert( MusicCd aCd )
              MusicCdNode cdNode = new MusicCdNode( aCd );
              cdNode.setNext( head );
              head = cdNode;
              numberOfItems++;
         public MusicCd delete(String aCdsTitle)
                                                throws InvalidDataException
              MusicCdNode current = head;
              MusicCdNode previous = null;
              while( current != null
                    && current.getMusicCd().getCdTitle() != aCdsTitle)
                   previous = current;
                   current = current.getNext();
              if (current == null ) //not found
                   throw new InvalidDataException(aCdsTitle
                                 + " not found: cannot be deleted" );
              else
                   if( current == head )
                        head = head.getNext(); //delete head
                   else
                        previous.setNext( current.getNext() );
                   numberOfItems--;
                   return current.getMusicCd();
         public MusicCd modify(String anExistedCdsTitle, String aModifyCdsTitle)
                                   throws InvalidDataException
              MusicCdNode current = head;
              while( current != null
                    && current.getMusicCd().getCdTitle() !=  anExistedCdsTitle)
                   current = current.getNext();
              if ( current == null )
                   throw new InvalidDataException( anExistedCdsTitle
                                 + " not found: cannot be deleted" );
              else
                   MusicCd tempCd = new MusicCd();
                   tempCd.setCdTitle(aModifyCdsTitle);
                   current.setMusicCd(tempCd);
                   return current.getMusicCd();
    }//for better understand of my program
    public interface SortedListInterface<T>
         //public SortedList();
         public void insert( T anElement );
         public T delete(String searchKey)
                                         throws InvalidDataException;
         public T modify(String searchKey, String aModifyTitle)
                             throws InvalidDataException;
    public abstract class ShellSortedList
         protected MusicCdNode head;
         protected int numberOfItems;
         public ShellSortedList()
              head = null;
              numberOfItems = 0;
         public int getNumberOfItems()
              return numberOfItems;
         public boolean isEmpty()
              return( numberOfItems == 0 );
         public boolean isDuplicate(String newCD)
                boolean found = false;
                MusicCdNode current = head;
                for( int i=0; i < numberOfItems; i++)
                   if(current.getMusicCd().getCdTitle().equals(newCD))
                   System.out.println("Duplicate Cd is found !!");
                            found = true;
                   current = current.getNext();
                    return found;
         public String toString()
              String listString = " ";
              MusicCdNode current = head;
              for( int i=0; i < numberOfItems; i++)
                   listString += current.getMusicCd().toString() + "\n";
                   current = current.getNext();
              return listString;
    public class MusicCdNode
         private MusicCd cd;
         private MusicCdNode next;
         // Default constructor
         public MusicCdNode()
         // Description: Initialize the reference for the cd object and the value of next to null.
         // Postcondition: cd = null; next = null;
              cd = null;
              next = null;
         // Parameterized constructor
         public MusicCdNode(MusicCd aCd)
         // Description: Set the reference for the cd object according to the parameters and value of next to null.
         // Postcondition: cd = aCd; next = null;
              cd = aCd;
              next = null;
           public MusicCd getMusicCd()
              return new MusicCd(cd.getCdTitle());
         public MusicCdNode getNext()
              return next;
         public void setMusicCd(MusicCd aCd)
              cd = new MusicCd(aCd.getCdTitle());
         public void setNext(MusicCdNode aCd)
              next = aCd;
    // File: MusicCd.java
    // Author: Chi Lun To (Ivan To)
    // Created on: June 5, 2007
    // Class Description
    // The MusicCd class defines a music cd object that contain the CD`s title, CD`s artist/GroupName,
    //  CD`s yearOfRelease , Cd`s music genre, and any comment of the Cd`s. This class provides functions
    //  to access the musicCdsTitle, artistOrGroupName, yearOfRelease, musicGenre, and aComment variable.
    //  Class Invariant: All MusicCd objects have a  string musicCdsTitle, string artistOrGroupName, integer yearOfRelease
    //  String musicGenre, and String aComment. A string type musicCdsTitle,artistOrGroupName, musicGenre,or aComment of "None"
    //  indicates no real name specified yet. A integer yearOfRelease of 1000 indicates no real years specific yet.
    public class MusicCd
         String theCdTitle;// the CD`s Title
         // Default constructor
         public MusicCd()
         // Description: Initialize theCdTitle to empty string
         // Postcondition: theCdTitle = " ";
              theCdTitle = " ";
         }//end constructor
         // Parameterized constructor
         public MusicCd(String aCdTitle)
         // Description: Set theCdTitle according to the parameters
         // Postcondition: theCdTitle = aCdTitle;
              theCdTitle = aCdTitle;
         } // end constructor
         // Accessor function : getCdTitle( ) function
         public String getCdTitle()
         // Description: Method to return the theCdTitle
         // Postcondition: the value of theCdTitle is returned
              return theCdTitle;
         }// end  getCdTitle( ) function
         // Mutator function: setCdTitle( ) function
         public void setCdTitle(String aCdTitle)
         // Description: Method to set theCdTitle according to the parameter
         // Postcondition: theCdTitle = aCdTitle;
              theCdTitle = aCdTitle;
         }// end setCdTitle( ) function
         // toString( ) function
         public String toString()
         // Description: Method to return the theCdTitle
         // Postcondition: the value of theCdTitle is returned as String
                   return("Title: " + theCdTitle );
         }// end  toString( ) function
    // File: InvalidDataException.java
    // Author: Chi Lun To (Ivan To)
    // Created on: June 5, 2007
    // Class Description
    // The InvalidDataException class is a self- defined exception class which handles
    // the issues that may arise with return value of the deleted and modify function.
    // For example,  the issue will occurs if the user try to delete the music cd from a empty list
    // or deleting a music cd that does not exist on the list. it would return null to the user. But, the user
    // expected to return an obeject reference of the music cd.Therefore, we instantiate InvalidDataException
    // class to handle this issue.
    //  Class Invariant:
    //  InvalidDataException class is a self-defining exceptional class which
    //  inherits the existing functionality of the Exception class.
    public class InvalidDataException extends Exception
         //Parameterized constructor
         public InvalidDataException( String s )
              super( s ); //inherits the existing functionality of the Exception class.
    }Message was edited by:
    Ivan1238
    Message was edited by:
    Ivan1238

    thx for your suggestion ..but i did try to skip my code..but i am sure if u guy understand what i am trying to ask ..so i try to show my all program for u guy better undrstand my problem ...the first three paragraph of code i hope u guy could focus on it ....i try ask the user to input the cd`s title to our insert list by using a function call readString( ) and i use this method to ask the user what cd they want to be delete from the list ...but it doesn`t work when i try to perform the delete cd funtion. At first, i think it should be my deleteCd( ) problem ..but i do some testing on it..it works fine if i pass a String directly to my function instead of using readString() function to perform ...therefore, i am sure my delete function working fine....i am thinking if it is my readString() problem make my deletion does not perform well...thx for u guy help

  • Question abput Extending Classes

    Hi,
    Would anyone know if the following is valid??
    class A extends B{}
    class B extends A{}
    Thanks in advance...

    It is a cyclic inheritance error if a class or interface inherits from itself, even directly (i.e., it appears as its super-class or in its list of super-interfaces) or indirectly (i.e, one of its super-class or one of its super-interfaces inherits from it)A cyclic inheritance error is reported

  • Queue Reference Based issued

    Hi all..could anyone tell me how i should fix the problem that i am struck here? I try to implemented an queue on my own. but i change sth in that queue.. i try not to use isEmpty() to keep track of the element in my queue..(it work fine if i use isEmpty()....) instead of using size() to keep track if it is an empty stack...but i got a little bit problem here..it call the exception automatically..and i am not expecting this result
    =========================
    javac QueueTest.java
    Exit code: 0
    java QueueTestThe queue is empty
    0 1 2 3 4 5 6 7 8
    EmptyQueueException on peek:queue empty <<- error occur here.ithould not appear.
    Exit code: 0=====================
    expected result
    =========================
    javac QueueTest.java
    Exit code: 0
    java QueueTestThe queue is empty
    0 1 2 3 4 5 6 7 8
    Exit code: 0=====================
    my code is as following
    QueueTest
    public class QueueTest
         public static void main(String[] args)
              QueueReferenceBased aQueue = new QueueReferenceBased();
              if(aQueue.size() == 0)
              //if(aQueue.isEmpty())
                   System.out.println("The queue is empty");
              for(int i=0; i < 9; i++)
                   aQueue.enqueue(new Integer(i));
              try
                 //while (!aQueue.isEmpty())     
                 //while(aQueue.size() != 0)
                 while(aQueue.size() != 0)
                      System.out.print(aQueue.peek() + " ");
                      //System.out.print(aQueue.size() );
                      aQueue.dequeue();
                // System.out.print(aQueue.size() );
              //aQueue.peek();
              catch( EmptyQueueException eqe)
                   System.out.println("\n" + eqe.getMessage());
    }===
    QueueReferenceBased
    // File: QueueReferenceBased.java
    // Author: Chi Lun To (Ivan To)
    // Created on: June 5, 2007
    public class QueueReferenceBased implements QueueInterface
      private Node lastNode;
      private int numberOfItems = 0;
      public QueueReferenceBased()
          lastNode = null;  
      // queue operations:
      public boolean isEmpty()
        return lastNode == null;
      public int size()
           return numberOfItems;
      public void enqueue(Object newItem)
      { // insert the new node
        Node newNode = new Node(newItem);           
       // if (isEmpty())
        if(lastNode == null)
      // if(size()==0)
               // insertion into empty queue
              newNode.setNext(newNode);
        else {
              // insertion into nonempty queue
              newNode.setNext(lastNode.getNext());
               lastNode.setNext(newNode);
        lastNode = newNode;  // new node is at back
          numberOfItems++;
      public Object dequeue() throws EmptyQueueException
          // if(!isEmpty())
    //if (!(size() == 0))
    if(lastNode != null)
               // queue is not empty; remove front
               Node firstNode = lastNode.getNext();
               if (firstNode == lastNode)             // special case?
                        lastNode = null;                  // yes, one node in queue
              else
                        lastNode.setNext(firstNode.getNext());
                        numberOfItems--;
              return firstNode.getItem();
        else {
              throw new EmptyQueueException("EmptyQueueException on dequeue:" + "queue empty");
      }  // end dequeue
      public Object peek() throws EmptyQueueException
          if(lastNode != null)
          //if (size() != -1)
          // queue is not empty; retrieve front
          Node firstNode = lastNode.getNext();
          return firstNode.getItem();
        else {
          throw new EmptyQueueException("EmptyQueueException on peek:"+ "queue empty");
    } // end QueueReferenceBased===
    the code u could omit ..but just for better unstanding ..thx
    node
    public class Node {
      private Object item;
      private Node next;
      public Node(Object newItem) {
        item = newItem;
        next = null;
      } // end constructor
      public Node(Object newItem, Node nextNode) {
        item = newItem;
        next = nextNode;
      } // end constructor
      public void setItem(Object newItem) {
        item = newItem;
      } // end setItem
      public Object getItem() {
        return item;
      } // end getItem
      public void setNext(Node nextNode) {
        next = nextNode;
      } // end setNext
      public Node getNext() {
        return next;
      } // end getNext
    } // end class Node====
    QueueInterface
    public interface QueueInterface
      //public boolean isEmpty() ;
      public int size();
      // Description: Determines the number of elements in a queue.
      //                    In other words, the length of a queue.
      // Precondition: None.
      // Postcondition: Returns the number of elements that are
      //                        currently in the queue.
      // Throws: None.
      public void enqueue(Object newElement);
      // Description: Adds an element at the back of a queue.
      // Precondition: None.
      // Postcondition: If the operation was successful,
      //                        newElement is at the back of the queue.
      // Throws: None.
    public Object dequeue() throws EmptyQueueException;
      // Description: Retrieves and removes the front of a queue.
      // Precondition: Queue is not empty.
      // Postcondition: If the queue is not empty, the element
      //                       that was added to the queue earliest
      //                       is returned and the element is removed.
      //                       If the queue is empty, the operation
      //                       is impossible and QueueException is thrown.
      // Throws: EmptyQueueException when the queue is empty.
      public Object peek() throws EmptyQueueException;
      // Description: Retrieves the element at the front of a queue.
      // Precondition: Queue is not empty.
      // Postcondition: If the queue is not empty, the element
      //                        that was added to the queue earliest
      //                        is returned. If the queue is empty, the
      //                        operation is impossible and QueueException
      //                        is thrown.
      // Throws: EmptyQueueException when the queue is empty.
    }  // end QueueInterface=====
    public class EmptyQueueException extends Exception
         //Parameterized constructor
         public EmptyQueueException( String s )
              super( s ); //inherits the existing functionality of the Exception class.
    }

    i try not to use isEmpty() to keep track of the
    element in my queue..(it work fine if i use
    isEmpty()....) instead of using size() to keep track
    if it is an empty stack... and this is a complete red herring. isEmpty() just returns size() == 0. The two are completely equivalent and there is no possibility that one worked when the other didn't.

  • Data Modeler: Super Type and Inheritance when engineered to Relational Mode

    PLEASE IGNORE THIS MESSAGE, I'VE SORTED IT. MY STUPIDITY HAS BEEN RECTIFIED BY READING THE MANUAL!!
    Hi
    I have a logical model that I'm playing with where I want to set a super type entity that contains common columns for all sub-type entities a la java inheritance.
    When I engineer this with the super type entity method set to 'Table for each entity' it creates a table for the super and sub entities and links them with a PK-FK.
    That's not what I was expecting.... I would like to get :
    PARENT ENTITY (Super Type)
    ATTRIBUTE1
    ATTRIBUTE2
    and
    CHILD ENTIRY (Super Type = PARENT ENTITY)
    CHILD_ID PK
    DESCRIPTION
    when this is engineered I'd like:
    TABLE = CHILD_ENTITY
    Columns:
    CHILD_ID PK
    DESCRIPTION
    ATTRIBUTE1
    ATTRIBUTE2
    Any ideas what I'm going wrong here????
    Cheers
    Chris
    Edited by: chriseb on Aug 13, 2009 2:46 PM

    Hi Chris,
    I'm glad that you have sorted it out. Then you can mark the question as answered.
    Philip

  • Regarding Inheritance (and super)

    Let:
    class A { ... }
    class B extend A { ... }
    From within class B, the super keyword allows me to access the visible methods and variables in A. However, super does not seem to be a reference; that is, while I can legally do
    Object a = this;
    I cannot do
    Object a = super;
    But, I would really like to be able to do this. That is, from the context of B, I would like to obtain a reference to the supertype, such that (ref instanceof A == true), (ref instanceof B == false). In short, I want a 'super' that behaves exactly like a 'this'. The ultimate goal of this is to pass a reference to the supertype into a method (say, a static method). Is this at all possible in Java? My only idea at the moment is to create a new instance of the superclass and set all of its state correctly, pass this instance into the desired method, then reestablish state once the method returns. Sounds painful and error-prone, though.
    Thanks for any ideas.

    sancho_panza wrote:
    ejp wrote:
    Why? Any method will already accept a reference to B as a reference to A, if B extends A.I am performing a transformation on Java classes that involves turning instance methods into static methods. It is not problem to pass a reference to 'this' into such a static method. But what if the instance method invokes super? Super cannot be invoked statically; thus I would like to pass 'super' into this method, which is impossible. I suppose creating a temporary container for the superclass is the easiest way (though it seems like this should be a lot easier).To do this you need to transform the Java static inheritance to a dynamic equivalent. This is quite straightforward. Say you have,
    class A {}
    class B extends A {}Now the A class is split into an interface A and an implementation class A_IMPL. You get this,
    interface A {}
    class A_IMPL implements A {}
    class B implements A {
       private A a_ref = new A_IMPL(); // object holding implementation of A
       // The implementation of inherited A methods is delegated to the A_IMPL object
    }In the above a_ref is the super reference you desired.

  • Can defualt inherited the Super Class constructor to sub class ?

    Hi,
    is it passible to inherit the super class constructor by defualt when extends the super class.
    Thanks
    MerlinRoshina

    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Inherited methods of super class not shown in outline

    Hello, is there a possibility to display the methods and variables from the super class in the outline of the inheriting class in AiE?

    Hi Christian,
    We had discussed this, when we implemented the outline and quick outline some years, ago. Finally, we sticked to the approach that is used by other plug-ins in Eclipse (like JDT).
    There Outline View shows only the content of the current editor. This helps to keep the content of the view stable when you select an element for navigation (because you won't be able to switch the editor by selecting an element ).
    Inherited members are usually part of other editors, unless you have redefined a method in your current class. Therefore, they are not shown in Outline View (unless they are redefinitions).
    The filters like "Hide Non-Public Members of classes" can only hide elements of the current editor.
    Inherited members can be shown in the Quick Outline, because the interaction pattern is different there: If you navigate to an element the pop-up is closed. Therefore, a content change of the Quick-Outline does not hurt.
    Michael

  • Multiple inheritance and super

    How to I get to a super function when using multiple inheritance? For example, the code below doesn't compile if Human extends Job, but works fine if Human only extends Animal.
    package test;
    import java.lang.System;
    public class Job {
    public class Animal {
    public attribute isStanding:Boolean = false;
    public function printStatus():Void {
    System.out.println( if (isStanding) "Standing up" else "Laying down");
    public class Human extends Animal, Job {
    public attribute isAtWork:Boolean = false;
    public function printStatus():Void {
    System.out.println( if (isAtWork) "At the office" else "At home");
    super.printStatus();
    var person:Human = Human{};
    person.printStatus();

    Thanks! Works great. I never even tried that since my brain is wired to only use that syntax for calling a static method/function/field.
    Note: If you change the class definition in the original sample from
    public class Human extends Animal, Job {topublic class Human extends Animal {The original compiles and runs as you'd expect. So the 'super' keyword exists in some form and has the expected result for singular inheritance when used to call parent methods. I think you are thinking of using it to call constructors. In that usage I think you are right that it doesn't work at all in JavaFX.

  • Inheriting and the "super" keyword

    I found a case where "super" is not working as I understand it should...
    Can someone explain me the underlying theory that makes JAVA behave this way??
    public class Base {
         public void method1() {
              System.out.println("method1 from \"Base\" class. About to call method2.");
              method2();
         public void method2() {
              System.out.println("method2 from \"Base\" class. About to call method3.");
              method3();
         public void method3() {
              System.out.println("method3 from \"Base\" class.");
    public class Extension extends Base {
         @Override
         public void method1(){
              System.out.println("method1 from \"Extension\" class. About to call super.method2.");
              super.method2();          
         @Override
         public void method2(){
              System.out.println("method2 from \"Extension\" class. About to call method3.");
              method3();          
         @Override
         public void method3(){
              System.out.println("method3 from \"Extension\" class.");                    
    public class Main {
         public static void main(String args[]) {
              System.out.println("In \"The Java Programming Language,\n" +
                        "Fourth Edition By Ken Arnold, James Gosling, David Holmes\"\n"+
                        "chapter: 3.3: \"Inheriting and Redefining Members\""+
                        " says:");
              System.out.println("Using super is the only case in which the type of\n" +
                        "the reference governs selection of the method implementation\n" +
                        "to be used. An invocation of super.method always uses the\n" +
                        "implementation of method the superclass defines (or\n" +
                        "inherits). It does not use any overriding implementation of\n" +
                        "that method further down the class hierarchy.\n");
              System.out.println("But by running this code, i get:");
              System.out.println("------------------------------------------");          
              Extension ext = new Extension();
              ext.method1();          
              System.out.println("------------------------------------------");
              System.out.println("\nWHY??? I was expecting:\n"+
                        "method1 from \"Extension\" class. About to call super.method2.\n" +
                        "method2 from \"Base\" class. About to call method3.\n" +
                        "method3 from \"Base\" class.");          
    THANKS!!

    IgnacioKriche wrote:
    But I used "super", so this means to use the methods of the super class and I understand that a method called within another, is part of this last one. this is:
    if inside method 'x', method 'y' is called, then 'y' is part of 'x' . Agree? And therefore since I am using super I'm saying use 'x' method from super class since 'y' is part of 'x' then super applies for 'y' as well so what is method from the extended class doing here? It's like we have a mix between the 'x' from super and 'y' from the extended. Something like super only applies for the first level not at a deeper level (a method called from another)No. Just because the base class method2() invokes method3() does NOT mean it will always invoke base's version of method3. If it did that, then polymorphism would definitely be broken.
    You explicitly invoked super.method2(), so that told the compiler to explicitly use the base class version of that method. But then method2 in the base class invokes method3(). That ends up invoking the overridden version in the subclass, by design, because afterall the actual object whose methods are being executed is a subclass instance. If it didn't do that, then polymorphism would be broken for everyone else.
    If you think you need the behavior you are looking for, you are just designing it wrong in the first place.

  • Inheritance and super usage help

    so i have a parent class called Gun and i have a protected field called bulletsInGun in the constructor and then i have a a subclass called HandGun that inherits from the Gun class and i am trying to used the field bulletsInGun in the parents class constructor for the HandGun subclass constructor. how would i do that? i tried super.bulletsInGun and i tried super(bulletsInGun) and none of them work i keep getting "not a statement error".

    this is my gun class the parent class
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package javaapplication1;
    * @author steven
    abstract public class Gun {
        private int numberOfBulletsAllowedInGun;
        private int bulletsInGun;
        protected static final int NUMBEROFBULLETSMAX = 0;
        public Gun()
            numberOfBulletsAllowedInGun= 0;   
            bulletsInGun = 0;
         * this method should reload the bullet.
        public void shoot()
            if(bulletsInGun <= 0)
            cannotFire();
            else
                typeOfShotInitated();
        public void cannotFire(){
            System.out.println("No, more bullets cannot fire must reload.");
       abstract public void typeOfShotInitated();
       abstract public void reload();
    }this is the subclass that inheritances from the gun class
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package javaapplication1;
    * @author steven
    public class HandGun extends Gun{
                /*how do i bring in "protected static final int NUMBEROFBULLETSMAX = 0;" from the parent class into each of the subclasses that i make? */
        public HandGun(){
            super(bulletsInGun);                                   // how do i add these fields from the Gun class?
            super(numberOfBulletsAllowedInGun);         //
        public void reload(){
            if(bulletsInGun == )
            bulletsInGun += 9;
        public void typeOfShotInitated(){
    }

  • How to inheritance a super class without no-argument constructor

    i try to inheritance javax.swing.tree.DefaultTreeModel:
    public class myTreeModel extends DefaultTreeModel
    but the compiler say:
    'constructor DefaultTreeModel() not found in class javax.swing.tree.DefaultTreeModel'
    and stoped.
    How can I get around this?
    THANK YOU for your consideration.

    Inside myTreeModel, i tried several things:
    1. add a no-argument constructor;
    Your no argument constructor should be either one of the below :
    public myTreeModel() {
       super(new DefaultMutableTreeNode());
    public myTreeModel() {
       super(new DefaultMutableTreeNode(), true);
    2. add a contructor with (DefaultTreeNode) argument;
    Your constructor with tree node argument should be either one of the below :
    public myTreeModel(DefaultMutableTreeNode node) {
       super(node);
    public myTreeModel(DefaultMutableTreeNode node) {
       super(node, true);
    }You would get an error if you did the following:
    public myTreeModel() {
    public myTreeModel(DefaultMutableTreeNode node) {
    }In both of the cases the default no arguement constructor of the super class is called implicitly like:
    public myTreeModel() {
       super();
    public myTreeModel(DefaultMutableTreeNode node) {
       super();
    }In this case the call super() is refering to a no arguement constructor in DefaultTreeModel. However, no such constructor exists in the DefaultTreeModel class resulting in a compile time error.
    Note: You do not need to use DefaultMutableTreeNode. You an use some other class that implements the TreeNode interface.

  • Recursive get inheritance family , but It stop at It's super class.

    I make this class for the purpose to getting specified class name's inheritance family.
    import java.util.*;
    import java.lang.reflect.Field;
    // A simple class for getting specify class name's super class family.
    // Usage: java GetSuperClass java.util.ArrayList.
    public class GetSuperClass {
      //recursive get super class.
      public static void get(String str) {
        Class ref = null;
        try {
          // get Class Objcet.
          ref = Class.forName(str);
        } catch(ClassNotFoundException e) {
          e.printStackTrace(System.err);
          System.exit(0);
          System.out.println(ref);
          System.out.println("field:");
          // get fields
          Field[] field = ref.getDeclaredFields();
          for(int i = 0; i < field.length; i++) {
            System.out.println(field);
    //get super class
    Class superClass= ref.getSuperclass();
    //recursive call get()
    if(superClass != null) {
    get(superClass.toString());
    return;
    public static void main(String[] args) {
    // must input a class name for getting super class family.
    if(args.length != 1) {
    System.out.println("incorrect parameters");
    System.exit(0);
    // call static method to start.
    get(args[0]);
    Input as into console command prompt.
    java GetSuperClass java.util.ArrayListHere is result:
    class java.util.ArrayList
    field:
    private static final long java.util.ArrayList.serialVersionUID
    private transient java.lang.Object[] java.util.ArrayList.elementData
    private int java.util.ArrayList.size
    java.lang.ClassNotFoundException: class java.util.AbstractList
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:164)
    at GetSuperClass.get(GetSuperClass.java:9)
    at GetSuperClass.get(GetSuperClass.java:23)
    at GetSuperClass.main(GetSuperClass.java:33)
    Question: what's wrong with it?
    Thanks for your response.

    No need to lokup the super class! You already have it!
    import java.util.*;
    import java.lang.reflect.Field;
    // A simple class for getting specify class name's super class family.
    // Usage: java GetSuperClass java.util.ArrayList.
    public class GetSuperClass
        public static void get(String str)
            Class ref = null;
            for (ClassLoader cl = GetSuperClass.class.getClassLoader(); cl != null; cl = cl.getParent())
                try
                    // get Class Objcet.
                    ref = Class.forName(str, false, System.class.getClassLoader());
                catch(ClassNotFoundException e)
                    //e.printStackTrace(System.err);
            get(ref);
        private static void get(Class ref)
            System.out.println(ref);
            System.out.println("field:");
            // get fields
            Field[] field = ref.getDeclaredFields();
            for(int i = 0; i < field.length; i++)
                System.out.println(field);
    //get super class
    Class superClass= ref.getSuperclass();
    //recursive call get()
    if(superClass != null)
    get(superClass);
    return;
    public static void main(String[] args)
    // call static method to start.
    get("java.util.ArrayList");

  • Super & inheritance

    I know (?) that private data is not inherited by subclasses.
    Consider the following...
    public class InheritanceTest
         static public void main(String args[])
              Car           a = new Car();
              FordFocus     b = new FordFocus();
              System.out.println("Car has " + a.getDoors() + " doors.");
              System.out.println("Ford Focus has " + b.getDoors() + " doors.");
    class Car
         private int doors;
         public Car()
              doors = 4;
         public int getDoors()
              return doors;
    class FordFocus extends Car
         public FordFocus()
              super();
    }This code compiles and produces the following output:
    Car has 4 doors.
    Ford Focus has 4 doors.
    But, if I override getDoors with a new method containing the exact same code within the FordFocus class, it bombs at compile citing "doors has private access in Car", as I would expect.
    I'm somewhat confused as to what "inherits" means. I wouldn't have thought this code example would have worked, due to doors being private. Unfortunately, the books I have and the documentation I have been able to uncover does not shed much light on this, and the only play I have ever seen this come into play (Come on people, use PROTECTED! lol) was of course in an exam question.
    Anyone have some insight to share on the nature of super and the inheritance or lack thereof of private class members, or could someone perhaps point me at some documentation that covers this in detail or explains what happens behind this code that might make some sense?
    Thanks in advance!
    - Kyle

    This code compiles and produces the following output:
    Car has 4 doors.
    Ford Focus has 4 doors.
    But, if I override getDoors with a new method
    containing the exact same code within the FordFocus
    class, it bombs at compile citing "doors has private
    access in Car", as I would expect.
    I'm somewhat confused as to what "inherits" means.It means it's in the superclass or superinterface, it's accessible (not private or package-private), and it's not hidden or overridden by a member of the same name in this class.
    I
    wouldn't have thought this code example would have
    worked, due to doors being private. But Focus isn't accessing doors. Focus is inheriting Car's getDoors method. It's public in Car, so it's public in Focus. However, since it's implemented in Car, that implementation has access to Car's private members.
    class members, or could someone perhaps point me at
    some documentation that covers this in detail or
    explains what happens behind this code that might
    make some sense?Here's the ultimate source, but it's not necessarily easy reading:
    [url http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html]JLS
    [url http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4]JLS 6.4 Members and Inheritance
    [url http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4.3]JLS 6.4.3 The Members of a Class Type
    [url http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.2.1]JLS 8.2.1 Examples of Inheritance
    If that reading is too dry, one or more of the following probably has some more digestible info:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.
    James Gosling's The Java Programming Language. Gosling is
    the creator of Java. It doesn't get much more authoratative than this.

  • Using inherited fields from a non entity super class in a compound PK class

    Hi,
    Suppose you have a POJO class called BaseClass, which is decorated with @MappedSuperclass, so that its sub classes can become EJB entities:
    @MappedSuperclass
    public class BaseClass implements Serializable {
    protected int field1;
    protected int field2;
    }EntityOne class is a sub class of BaseClass and an EJB 3.0 entity.
    @Entity
    public class EntityOne extends BaseClass {
    @Id
    protected int field3
    }Everything would be fine up to this point. The problem begins when the following situation is given:
    EntityOne shall have a compound primary key, which is a combination of filed1, field2 and field3!
    Off course, I can define a primary key class EntityOnePK:
    public class EntityOnePK implements Serializable {
      protected int filed1;
      protected int filed2;
      protected int filed3;
      public int hashCode(){...}
      public boolean equals(....){....}
    }But the fields 1 and 2 can not be decorated with @Id annotation, since they are not defined in an entity class!
    Any ideas of how to resolve this situation?
    I had a look in the specification and some articles. I have to admit that the new inheritance features in the EJB 3.0 framework are a real improvement . However, in a bigger scale application, where persistence is only one of many aspects of the system, the introduced methodology of inheritance is not sufficient, i.e. the BaseClass has a lot of subclasses and is used in many packets as a POJO.
    To be more concrete, in our case there are good reasons not define the base class as an entity, mainly to avoid a corresponding table in the used DB, which is also interfacing with other software systems.
    Thanks in advance for your help,
    Mehran

    JAZN is indeed supported for a standalone client. Make sure that the client JVM is also configured for JAAS and has jazn.jar in the classpath.
    Regards,
    -Lee

Maybe you are looking for

  • AppleTV's streaming issues... are there limits ?

    I had 2 appletv's (v2) connected to an iMac (3GHz intel cores i3 with 4 gb of memory) which in turn is hard wired into a linksys router which has an  8TB Buffalo NAS device on it which stores approx 2.5GB of media... mostly movies and TV shows... all

  • Interpreting a field in an equation

    I need to use a value from a field as an operator in an equation. Example: the field holds values like '<' or '>' in the select statement I want to compare two values using this operator something like table.value1 > table.value2 How do I replace the

  • Imac 27 - new problem - screen moved up and dock in the middle.

    I was wondering if any of you had this problem as well. I restarted already comp and everything seems to be ok (question for how long), at this moment but just few min ago I had a dock horizontally in the middle of my screen with black and white stri

  • Solaris Patching/SAN Boot

    I have just created an ABE on a SAN device, upgraded it and then booted from it. Its been a long journey, and involved a SR with oracle. I was new to it and am astonished at how hard it has been. Not hard in the sense that anything was over complicat

  • Why does time machine go back less than a month?

    clearly, i'm doing something wrong... i'm in the process of cleaning up stuff from my external drives.  sometime in the fall, i switched my time machine backup to a larger drive.  i did my best to follow the instructions for transferring over a time