Superclass Constructor calling overridable validation method

I have the following class:
public class SuperClass
   private int x;
   public SuperClass(int x)
      setX(x);
   protected void validateX(int x)
      if(x < 0)
         throw new IllegalArgumentException("x < 0");
   public int getX()
      return x;
   public void setX(int x)
      validateX(x);
      this.x = x;
}My question is: How can I avoid calling setX(int) in the constructor besides simply dupicating validateX(int) in the constructor if I want to subclass SuperClass? [I read in a recent Java Fundamentals newsletter that calling overridable methods in superclass constructors is a bad idea int that it tends to destabilize the whole class hierarchy.  I don't want to make validateX(int) and setX(int) final.]

Never call overrideable methods from constructors. No exceptions.
You can use a factory method to validate your object after its created if you must.
public class SuperClass
   private int x;
   public SuperClass()
   static SuperClass createSuperClass(int x){
         SuperClass sc = new SuperClass();
         sc.setX(x);
         return sc;
   protected void validateX(int x)
      if(x < 0)
         throw new IllegalArgumentException("x < 0");
   public int getX()
      return x;
   public void setX(int x)
      validateX(x);
      this.x = x;
}Or you can use template method
public class SuperClass
private int x;
public SuperClass(int x)
setXImpl(x);
final protected void validateX(int x)
if(x < 0)
throw new IllegalArgumentException("x < 0");
public int getX()
return x;
final void setXImpl(int x){
validateX(x);
this.x = x;
public void setX(int x)
setXImpl(x);
In general I don't like to call any overrideable methods from within my class. I try not to be anal about it though. My personal choice would be to duplicate the set method in the constructor. You should be constructing the object not using it. access instance variables not methods.

Similar Messages

  • Subclassing constructor to override a method?

    How would I create a subclass of the Contains query and override the expand() method? How would I do this any code examples, anything.
    I'm very new to java so any help would be great.
    Constructors
    Contains (StringAttribute, String, InstanceMetaData)
    public Contains(StringAttribute att, java.lang.String val, InstanceMetaData instmd)
    This constructs a contains query on a string attribute.
    Contains (String, InstanceMetaData)
    public Contains(java.lang.String val, InstanceMetaData instmd)
    This constructs a contains query on the document content.
    Methods
    compile()
    public java.lang.String compile()
    This compiles into a query string.
    Specified By:
    compile() in interface Query
    Returns:
    a query string representing this query.
    expand(StringAttribute, String, InstanceMetaData)
    public java.lang.String expand(StringAttribute att, java.lang.String str, InstanceMetaData instmd)
    This translates a user?s attribute Contains query string into a text query.
    Parameters:
    att - a string attribute
    str - the main query string
    instmd - the InstanceMetaData object
    Returns:
    The translated Oracle Text query string (contains clause)
    expand(String, InstanceMetaData)
    public java.lang.String expand(java.lang.String str, InstanceMetaData instmd)
    This translates a user query string into a text query.
    Parameters:
    str - the main query string
    instmd - the InstanceMetaData object
    Returns:
    The translated Oracle Text query string (contains clause)
    Thanks.

    I get the following error
    50
    [jsp src:line #:45]
    Return required at end of java.lang.String expand(java.lang.String, oracle.ultrasearch.query.InstanceMetaData). public java.lang.String expand(String a, InstanceMetaData b) { 
    52
    [jsp src:line #:47]
    Only constructors can invoke constructors. super(a,b);
    after adding:
    class myContains extends Contains {
    myContains(StringAttribute att, java.lang.String val, InstanceMetaData instmd) {
    super(att,val,instmd);
    myContains(java.lang.String val, InstanceMetaData instmd) {
    super(val,instmd);
    public java.lang.String expand(String a, InstanceMetaData b) {
    // your code here
    super(a,b);
    }

  • Superclass reference calls subclass's method..

    I have a doubt regarding the following..
    class A //super class
        public void ShowMessage()
            System.out.println("Inside A's showmessage");
    class B extends A //subclass
        public void ShowMessage()
            System.out.println("Inside B's showmessage");
        public void ShowAnotherMessage()
            System.out.println("Inside B's showanothermessage");
    class MainClass
        public static void main(String args[])
            A a; //plain reference
            B b=new B();
            a=b;
            a.ShowAnotherMessage(); //error, since it is not part of
    A
            a.ShowMessage(); //Actually calls B's version
    1. How do i make it call a's ShowMessage(). Is it possible with some typecast. What are the ways to call A's ShowMessage().
    2. The above is not a problem in C++, can use virtual functions to do it.
    [b]
    thanks...

    The behaviour you observe is correct. When a method is invoked the actual class of the object is used, when a variable is referenced the type of the reference determines the class. See section 3.3.3 of "The Java Programming Language" for more details. In C++ you must declare the method virtual to get this behaviour, in Java all methods are virtual.

  • EO Validation method called twice

    Hi,
    I have written an EO based field Validation method. But the problem is it is being called twice. First time ,it is validating correctly. But the second time it is not taking the field value and giving the error
    I have included it like this in my jspx.
    <af:inputText value="#{bindings.SubOrgName.inputValue}"
    label="#{bindings.SubOrgName.label}"
    required="#{bindings.SubOrgName.mandatory}"
    columns="#{bindings.SubOrgName.displayWidth}"
    binding="#{backing_Org.inputText3}"
    id="inputText3"
    rows="1">
    <af:validator binding="#{bindings.SubOrgName.validator}"/>
    </af:inputText>
    Please help.

    Thanks for sharing! ;-)

  • How to call a set method from within a constructor

    Hello,
    I want to be able to call a set method from within a Scanner, to be used as the argument to pass to the Scanner (from a source file). Here's what i tried:
    private void openFiles()
            input = new Scanner( setSource );              
        and here is the set method:
    public String setSource( String in )
            source = in;
            return source;
        }obviously there will be more code in this method but i'm trying to tackle one problem at a time. Thanks in advance..

    The "String in" declaration says: "Nobody may ever invoke setSource() without specifying a certain String. The content of the String is known at run-time only."
    In no place in your code you say the compiler: "I want the 'in' variable (actually, parameter) of method setSource() to contain the first arg which is passed to the application".
    This is exactly the same mechanism allowing you to write "new Scanner" with something inside the two parentheses.

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • Overriding static method

    hi all
    can be override static method.if yes then how?plz explain.

    Static methods do hide rather than override - the superclass-and-above methods are, however, visible via explicit referencing. Example:
    public class Foo
         public static final void main(String[] args)
              Foo.foo();
              Poo.foo();
              Foo.bar();
              Poo.bar();
         public static void foo()
              System.out.println("Foo foo");
         public static void bar()
              System.out.println("Foo bar");
         public static class Poo extends Foo
              public static void foo()
                   System.out.println("Poo foo");
              public static void bar()
                   System.out.print("Poo bar, calling foo(): ");
                   foo();
    }Gives
    Foo foo
    Poo foo
    Foo bar
    Poo bar, calling foo(): Poo fooAlways more interesting to try stuff and just see what happens, don't you think? :o)
    Message was edited by:
    itchyscratchy - line wrap pasting error

  • Override protected method as public

    I am new to Java.
    My doubt is :
    I have a class named Base having one protected method(let's say x()) and another class named Derived which extends Base.
    Now i want to override method x() of the Base class. Here I have 2 option either use access modifier as protected or public.
    As per my understanding, i can override this method only with exact signature. But I can use Public as well. And here i am getting confused why we can.
    Eg. In Object class we have method clone() which is protected, and to get cloned object of my class i need to override this method either with protected modifier or as public.
    If I override as public then whats the use of protected method, why its not defined as public.
    Please clear me the concept.

    cool_kkin wrote:
    As per my understanding, i can override this method only with exact signature. But I can use Public as well. And here i am getting confused why we can.Yes widening the scope is fine because the method still exists in the same nature as the method in the superclass. However narrowing the scope will hide for instance throw able exceptions from the caller, break polymorphism, conflict with the intension's of the class from the author and a whole wealth of other problems.
    If I override as public then whats the use of protected method, why its not defined as public. Not every class is sub classed, therefore the protected declaration acts as it should. The final declaration can also be used in conjunction with protected, making subclasses unable to widen the scope of protected, or even override the method to begin with.
    Mel

  • Overriding Inherited methods

    why cant we override the inherited methods with more secure access modifier (private)..... while if we do the apposite ie override with more non secure access modifiers , java is able to distinguish them and call the appropriate method or pop up the syntax error.. i am not able to understand the concept ... if any one could give a practical example it would helpful to me to understand...

    rajeshrocks25 wrote:
    Hey, correct me i am wrong.
    When we inherit Java loads all the members of the super class and we override or hide them then it simply ignores the superclass members ri8???
    thats what happening in the above code?I strongly suggest rereading the tutorial for Polymorphism or searching Google for alternative explanations for "Java Polymorphism", it doesn't sound like the concept has fully sunk in yet. As for a direct answer, at the bottom of the polymorphism tutorial I linked earlier they mention:
    The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.To add, if the object being referred to does not contain the appropriate method, then the JVM will look for an appropriate method in the superclass, and the superclass of the superclass until the appropriate method is found.
    Also to clarify your confusion earlier, if a subclass A extends a class B, then A is considered a B so there is no use in casting A to B. In a more practical sense, imagine a [Boy] extending a [Man]. The [Boy] is of course a [Boy] because that is what we have defined him as. But the [Boy] is also a [Man] because he extends the [Man]. Therefore casting a [Boy] into a [Man] is pointless, because he already is indeed a [Man], just a subclass in the form of a [Boy].
    Furthermore if we declare a [Man] and instantiate him with a [Boy] then invoking a method talk(), [Boy] is inspected for the appropriate method talk(), if it has not been overridden then the JVM will look in [Man] and calls the appropriate method. Alternatively if we declare a [Man] and instantiate him as a [Man] then invoking the method talk(), [Man] is inspected for the appropriate method. It might also be of worth to note the instantiated [Man] cannot be cast into a [Boy], because a [Boy] is a subclass of [Man] and may contain properties or methods undefined by [Man].
    Mel

  • Is not abstract and does not override abstract method actionPerformed

    I dont how to corr. Please help!! and thank you very much!!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class test extends JFrame implements ActionListener, ItemListener
              private CenterPanel centerPanel;
              private QuestionPanel questionPanel;
              private ButtonPanel buttonPanel;
              private ResponsePanel responsePanel;
              private JButton b1,b2,b3,b4,b5;               //Create five references to Jbutton instances
         private JTextField t1,t2,t3,t4,t5;          //Create five references to JTextField instances
              private JLabel label1;                    //Create one references to JLabel instances
              private JRadioButton q1,q2,q3;               //Create three references to JRadioButton instances
              private ButtonGroup radioGroup;               //Create one references to Button Group instances
              private int que1[] = new int[5];           //Create int[4] Array
              private int que2[] = new int[5];
              private int que3[] = new int[5];
              private String temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10,
                        temp11, temp12, temp13, temp14, temp15;
    public test (String header)
              super(header);
              Container container = getContentPane();
              label1 = new JLabel ("PLease click on your response to ");     
              q1 = new JRadioButton("I understand most of the content of this subject",true);
              add(q1);
              q2 = new JRadioButton("I see the relevance of the subject to my degree",false);
              add(q2);
              q3 = new JRadioButton("The workload in this subject is appropriate",false);
              add(q3);
              radioGroup = new ButtonGroup();               //JRadioButton belong to ButtonGroup
              radioGroup.add(q1);
              radioGroup.add(q2);
              radioGroup.add(q3);
              JPanel buttonPanel = new JPanel();
              JPanel responsePanel = new JPanel();
              JPanel questionPanel = new JPanel();
              JPanel centerPanel = new JPanel();
              b1 = new JButton ("Strongly DISAGREE");          //Instantiate JButton with text
              b1.addActionListener (this);               //Register JButtons to receive events
              b2 = new JButton ("DISAGREE");
              b2.addActionListener (this);
              b3 = new JButton ("Neither AGREE or DISAGREE");
              b3.addActionListener (this);
              b4 = new JButton ("AGREE");
              b4.addActionListener (this);
              b5 = new JButton ("Strongly AGREE");
              b5.addActionListener (this);
              buttonPanel.setLayout(new GridLayout(5,1));
              buttonPanel.add(b1);
              buttonPanel.add(b2);
              buttonPanel.add(b3);
              buttonPanel.add(b4);
              buttonPanel.add(b5);
              t1 = new JTextField ("0",3);               //JTextField contains empty string
              t2 = new JTextField ("0",3);
              t3 = new JTextField ("0",3);
              t4 = new JTextField ("0",3);
              t5 = new JTextField ("0",3);
              t1.setEditable( false );
              t2.setEditable( false );
              t3.setEditable( false );
              t4.setEditable( false );
              t5.setEditable( false );
              responsePanel.setLayout(new GridLayout(5,1));
              responsePanel.add(t1);
              responsePanel.add(t2);
              responsePanel.add(t3);
              responsePanel.add(t4);
              responsePanel.add(t5);
              questionPanel.setLayout(new GridLayout(4,1));
              questionPanel.add(label1);
              questionPanel.add(q1);
              questionPanel.add(q2);
              questionPanel.add(q3);
              centerPanel.add(buttonPanel,BorderLayout.CENTER);
              centerPanel.add(responsePanel,BorderLayout.EAST);
              container.add(centerPanel,BorderLayout.WEST);
              container.add(questionPanel,BorderLayout.NORTH);
              q1.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que1[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp1 = String.valueOf(que1[0]);
              t1.setText(temp1);
              else if (e.getSource() == b2)     {
                   que1[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp2 = String.valueOf(que1[1]);
              t2.setText(temp2);
              else if (e.getSource() == b3)     {
                   que1[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp3 = String.valueOf(que1[2]);
              t3.setText(temp3);
              else if (e.getSource() == b4)     {
                   que1[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp4 = String.valueOf(que1[3]);
              t4.setText(temp4);
              else if (e.getSource() == b5)     {
                   que1[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp5 = String.valueOf(que1[4]);
              t5.setText(temp5);
    } //end action performed
              q2.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que2[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp6 = String.valueOf(que2[0]);
              t1.setText(temp1);
              else if (e.getSource() == b2)     {
                   que2[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp7 = String.valueOf(que2[1]);
              t2.setText(temp7);
              else if (e.getSource() == b3)     {
                   que2[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp8 = String.valueOf(que2[2]);
              t3.setText(temp8);
              else if (e.getSource() == b4)     {
                   que2[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp9 = String.valueOf(que2[3]);
              t4.setText(temp9);
              else if (e.getSource() == b5)     {
                   que2[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp10 = String.valueOf(que2[4]);
              t5.setText(temp10);
    } //end action performed
              q3.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que3[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp11 = String.valueOf(que3[0]);
              t1.setText(temp11);
              else if (e.getSource() == b2)     {
                   que3[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp12 = String.valueOf(que3[1]);
              t2.setText(temp12);
              else if (e.getSource() == b3)     {
                   que3[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp13 = String.valueOf(que3[2]);
              t3.setText(temp13);
              else if (e.getSource() == b4)     {
                   que3[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp14 = String.valueOf(que3[3]);
              t4.setText(temp14);
              else if (e.getSource() == b5)     {
                   que3[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp15 = String.valueOf(que3[4]);
              t5.setText(temp15);
    } //end action performed
    }//end constructor test
    public void itemStateChanged(ItemEvent item) {
    //int state = item.getStateChange();
    //if (q1 == item.SELECTED)
              public class ButtonPanel extends JPanel
                   public ButtonPanel()
              public class CenterPanel extends JPanel
                   public CenterPanel()
              public class QuestionPanel extends JPanel
                   public QuestionPanel()
              public class ResponsePanel extends JPanel
                   public ResponsePanel()
    public static void main(String [] args)
         test surveyFrame = new test("Student Survey") ;
         surveyFrame.setSize( 500,300 );
         surveyFrame.setVisible(true);
         surveyFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
         }//end main
    }//end class test

    is not abstract and does not override abstract method actionPerformed
    Oh, I see that the title of your post is an error message? Ok. Well, the test class is declared as implementing an ActionListener. That means the test class must have an actionPerformed() method. Your test class apparently does not.
    It does not appear that the test class needs to implement ActionListener. You are using annonymous classes as listeners.

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Product is not abstract and does not override abstract method

    Received the following errors.
    Product.java:3: Product is not abstract and does not override abstract method ge
    tDisplayText() in Displayable
    public class Product implements Displayable
    ^
    Product.java:16: getDisplayText() in Product cannot implement getDisplayText() i
    n Displayable; attempting to use incompatible return type
    found : void
    required: java.lang.String
    public void getDisplayText()
    ^
    2 errors
    Code reads as follows
    import java.text.NumberFormat;
    public class Product implements Displayable
         private String code;
         private String description;
         private double price;
         public Product()
              this.code = "";
              this.description = "";
              this.price = 0;
    public void getDisplayText()
    String message =
    "Code: " + code + "\n" +
    "Description: " + description + "\n" +
    "Price: " + this.getFormattedPrice() + "\n";
         public Product(String code, String description, double price)
              this.code = code;
              this.description = description;
              this.price = price;
         public void setCode(String code)
              this.code = code;
         public String getCode(){
              return code;
         public void setDescription(String description)
              this.description = description;
         public String getDescription()
              return description;
         public void setPrice(double price)
              this.price = price;
         public double getPrice()
              return price;
         public String getFormattedPrice()
              NumberFormat currency = NumberFormat.getCurrencyInstance();
              return currency.format(price);
    Please help!

    Received the following errors.
    Product.java:3: Product is not abstract and does not
    override abstract method ge
    tDisplayText() in Displayable
    public class Product implements Displayable
    ^
    Product.java:16: getDisplayText() in Product cannot
    implement getDisplayText() i
    n Displayable; attempting to use incompatible return
    type
    found : void
    required: java.lang.String
    public void getDisplayText()
    ^
    2 errors
    Code reads as follows
    Please use the code tags when posting code. There is a code button right above the text box where you enter your post. Click on it and put the code between the code tags.
    These error messages are quite clear in telling what is wrong. You have an Interface called Displayable that specifies a method something like thispublic String getDisplayText() {But in your Product source code, you created thismethodpublic void getDisplayText() {The compiler is complaining because the methods are not the same.
    You also need to return a String in the method probalby like thisreturn message;

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Calling A Super Method Externally

    Hi,
    I would like to call an overridden method, a super method, of an object externally. I thought all I needed to do was:
    1. get the java.lang.Class object of the super class where the original method was declared and implemented.
    2. get the appropriate java.lang.reflect.Method object from the Class object.
    3. override the java language protections on the Method object.
    4. Call Method.invoke() with the instance of the subclass which I wanted to call the method on.
    Unfortunately, when I got to step 4, I saw this in the documentation for Method.invoke:
    "If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur."
    Is there any way to externally access the functionality of a super method implementation on a subclass that overrides it? It seems like there should be...
    In case you are wondering, the reason I am doing this is I am trying to implement a deep clone method. However, I would like any class to be able to call the deep clone method by passing themselves as an argument to a static method -- that way you don't have to worry about subclasses inheritting clone or anything like that. The code would look something like this (however it seems that according to the docs, this would result in an infinite recursion because when the Object.clone() method is invoked, it would actually resolve to the MyDeepCloneableObject.clone() method (which would call the utility function, which would invoke the Object.clone() again etc. etc.)):
    public class MyDeepCloneableObject implements Cloneable {
    public Object clone() {
    return ObjectUtil.deepClone(this);
    public class ObjectUtil {
    private static final Method OBJECT_CLONE_METHOD;
    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
    static {
    //Set the OBJECT_CLONE_METHOD
    try {
    OBJECT_CLONE_METHOD =
    Object.class.getDeclaredMethod("clone", EMPTY_CLASS_ARRAY);
    OBJECT_CLONE_METHOD.setAccessible(true);
    } catch (NoSuchMethodException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    } catch (RuntimeException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    public static Object deepClone(Cloneable object, int levels) {
    Object clone;
    try {
    clone = OBJECT_CLONE_METHOD.invoke(object, EMPTY_OBJECT_ARRAY);
    } catch (IllegalAccessException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    } catch (InvocationTargetException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    } catch (RuntimeException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    // Use more reflection on fields of clone to implement deep clone
    }

    In your example the clone method is not creating a clone, just returning a new instance of an object of the same type. In both cases the default shallow clone method should be implemented as follows:
    public Object clone() {
    //Call Object.clone()
    return super.clone;
    By doing so, any subclasses will also have their fields copied when clone() is called.
    From the javadocs for Object.clone():
    "The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation."
    Now as to how the parent is supposed to know about fields in subclasses, the implementation of clone is implemented in a native method in Object, so the JVM can pretty much know anything about the subobject as long as it has a reference to it. Further, if I wanted to make my own implementation, I could using reflection:
    public Object clone() {
    // Get the runtime class of this object, note that the runtime class
    // may be a subclass of the class in which this clone method is defined
    Class objectClass = this.getClass();
    //Get all of the fields in this class and it's super classes
    List fieldsList = new ArrayList();
    while (objectClass != null) {
    Field[] fields = objectClass.getDeclaredFields();
    for (int j =0; j < fields.length; j++) {
    fieldsList.add(fields[j]);
    objectClass = objectClass.getSuperClass();
    //Now I can create a new instance of the runtime class and set
    //all of its fields appropriately
    However, I'm sure the JVM's implementation is far more efficient.
    I have not benchmarked serialization. However, all the steps in my procedure would have to be done for serialization anyway (i.e. get list of all fields, instantiate equivalent field values and set them in the new object), but serialization also needs to convert everything to a byte representation and then parse it out again. Furthermore, serialization will perform a fully deep clone, where as I only want a one level deep clone (or two depending on how you think of it -- i.e. not a shallow copy of references (as Object.clone(0 does), but a copy of direct fields and containers (i.e. Maps and Collections in fields should be cloned, but not objects in the Maps and Collections). So if an object has a field which is a List and the List field contains 1 entry, and the object is cloned, then subsequent modifications to the List field in the cloned object are not reflected in the original object's List field and vice versa (i.e. the 1 entry is removed in the original , but remains in the clone's version of the List field).

  • How to force validator method instead of data type validation in af:table

    This post will probably once again illustrate exactly how new I am to the Java/JDeveloper world so thanks in advance for any help! I have tried searching but couldn't find anything that seemed to mirror my problem.
    I am using a modification of Frank's idea on how to individually color table cell backgrounds.
    http://thepeninsulasedge.com/frank_nimphius/2008/04/10/adf-faces-conditionally-color-table-cell-background-2/
    My intention was to use this along with custom validation to color cells with invalid values. It was a user request that it be done so as to quickly spot input errors (when updating records) if someone had missed the initial faces message and was no longer in the field that generated the error. It works fine for fields in my af:table based on VO attributes with varchar2 types but the 2 values with float and number types handle character input with a faces message "Not a number" and then do not seem to process the validator. The reason I (think I) need to use the validator in addition to Franks code is that in the validator code I use an addpartialtarget to the uicomponent that refreshes the background color if it changed in the backing bean.
    FYI the project is based on ADF BC/JSF.
    I tried gave the full use case as suggested so you understand what I am trying to accomplish and if you have a better way to accomplish this please let me know as well.
    Thanks,
    Rich
    Managed-Bean
        public String getMODELColorString() {
            MODELColorString = "width:125px;";
            Object MODEL = getRowValue("#{row.ModelType}");
            if (MODEL != null) {
                if (!isValidMODEL(MODEL.toString())) {
                    MODELColorString = "background-color:red;width:125px;";
            return MODELColorString;
        }Backing-Bean
            if (!myValidation.isValidMODEL(object.toString())) {
                System.out.println("InValid Data");
            AdfFacesContext.getCurrentInstance().addPartialTarget(uiComponent);P.S. If I made any newbie mistakes in my code please let me know, although this is obviously not production code yet by any means.
    Message was edited by:
    BengalGuy

    Frank (or anyone else who might offer some advice),
    I thought that solved my issue as I could see the validator getting triggered, however something else is now happening. It seems to pass through the validator once for each of the values on my table with the invalid input I entered on one of the numbers, "a" in this case, and then once again through the color change backing bean but at that time the invalid input reverts to the original input and the change is rendered on the af:table as well. Any thoughts ? I put a print in the validator method, in the method that gets called from the validator (checks to see if value can be converted to float) , and then the color change bean (which also calls the float validation test) and pasted the output below.
    Validator Triggered \Current Value = 0.037178375 \FloatTestOn: 0.037178375 \Result: Valid Data
    Validator Triggered \Current Value = 0.109212324 \FloatTestOn: 0.109212324 \Result: Valid Data
    Validator Triggered \Current Value = 0.18624917 \FloatTestOn: 0.18624917 \Result: Valid Data
    Validator Triggered \Current Value = 0.26863635 \FloatTestOn: 0.26863635 \Result: Valid Data
    Validator Triggered \Current Value = 0.35674548 \FloatTestOn: 0.35674548 \Result: Valid Data
    Validator Triggered \Current Value = -0.38118127 \FloatTestOn: -0.38118127 \Result: Valid Data
    Validator Triggered \Current Value = -0.3382032a \FloatTestOn: -0.3382032a NumberFormatException: For input string: "-0.3382032a"
    08/04/16 10:03:14 \Result: InValid Data
    Validator Triggered \Current Value = -0.29224017 \FloatTestOn: -0.29224017 \Result: Valid Data
    Validator Triggered \Current Value = -0.24308495 \FloatTestOn: -0.24308495 \Result: Valid Data
    Validator Triggered \Current Value = -0.1905158 \FloatTestOn: -0.1905158 \Result: Valid Data
    Validator Triggered \Current Value = -0.13429564 \FloatTestOn: -0.13429564 \Result: Valid Data
    Validator Triggered \Current Value = -0.07417088 \FloatTestOn: -0.07417088 \Result: Valid Data
    Validator Triggered \Current Value = -0.009870344 \FloatTestOn: -0.009870344 \Result: Valid Data
    \Checking for color change \FloatTestOn: 0.037178375
    \Checking for color change \FloatTestOn: 0.109212324
    \Checking for color change \FloatTestOn: 0.18624917
    \Checking for color change \FloatTestOn: 0.26863635
    \Checking for color change \FloatTestOn: 0.35674548
    \Checking for color change \FloatTestOn: -0.38118127
    \Checking for color change \FloatTestOn: -0.3382032 <- "a" is no longer there ?
    \Checking for color change \FloatTestOn: -0.29224017
    \Checking for color change \FloatTestOn: -0.24308495
    \Checking for color change \FloatTestOn: -0.1905158
    \Checking for color change \FloatTestOn: -0.13429564
    \Checking for color change \FloatTestOn: -0.07417088
    \Checking for color change \FloatTestOn: -0.009870344

Maybe you are looking for

  • TS1702 how can I get a refund on a product I didn't purchase?

    I have been billed twice for an in app product that I only bought once. How to get a refund from Itunes?

  • Use of  RFBIBL00 .,

    Hi All, Please let me know the use of program  RFBIBL00  .Is this can be used for Data conversion of GL Open Line items , Vendor Open Items, Customer  Open items. Please share the Useful Links . Please share advantage and disadvantage in Ecatt method

  • How do you get photos on you ipod nano

    mite seem like a think question but in the booklet it only tells me how to upload music how do i get photos on my ipod

  • QM Flexible Reports and Sample Archive

    Hi I'm looking for help in QM, regarding. 1) QM Flexible Reports with t-codes please. 2) Sample archive process with t-codes please. Thank you.

  • "moving point" pen tool bug

    Whenever i'm trying to draw a shape with the pen tool, the beginning pint will move or float away from the start point. Any idea why this happens?