Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: Not sure what type of variable to use.

  1. #1
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Not sure what type of variable to use.

    I'm not what type of variable to use to achieve my desired result.

    What I want is a variable that can be initialized differently in each instantiation of the class but cannot be reassigned another value after it has been initialized. In essence, I want a final-like variable whose value can differ between object of a given class.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Not sure what type of variable to use.

    You could initialize the final variable in the constructor. For example
    public class Example{
     
        final int value;
     
        public Example(int val){
            this.value = val;
        }
    }

  3. The Following User Says Thank You to copeg For This Useful Post:

    mjpam (July 8th, 2010)

  4. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Not sure what type of variable to use.

    Well, you can initialize a final in the constructor. I found this code online:
    // : c06:BlankFinal.java
    // "Blank" final fields.
    // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
    // www.BruceEckel.com. See copyright notice in CopyRight.txt.
     
    class Poppet {
      private int i;
     
      Poppet(int ii) {
        i = ii;
      }
    }
     
    public class BlankFinal {
      private final int i = 0; // Initialized final
     
      private final int j; // Blank final
     
      private final Poppet p; // Blank final reference
     
      // Blank finals MUST be initialized in the constructor:
      public BlankFinal() {
        j = 1; // Initialize blank final
        p = new Poppet(1); // Initialize blank final reference
      }
     
      public BlankFinal(int x) {
        j = x; // Initialize blank final
        p = new Poppet(x); // Initialize blank final reference
      }
     
      public static void main(String[] args) {
        new BlankFinal();
        new BlankFinal(47);
      }
    } ///:~

    source: Blank final fields : FinalLanguage BasicsJava

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    mjpam (July 8th, 2010)

  6. #4
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Not sure what type of variable to use.

    First , thank you for your helpful replies.

    This is actually for an assignment for an online course.

    This is what I have so far:

    import java.awt.*;
     
    class Rectangle
    {
         private int length;
         private int width;
         private int area;
         private int min = 10;
         private int max = 100;
         final int ID = 67;
         private Color color;
         private Graphics g;
     
     
         Rectangle()
         {
             length = min;
             width = min;
             color = Color.black;
         }
     
         Rectangle (int w)
         {
              if(w < min || w > max)
              {
                   System.out.print("Invalid dimesion");
                   System.exit(0);
              }
              else
              {
                   length = width = w;
              }
         }
     
         Rectangle (int l, int w)
         {
              if((w < min || w > max) || (l < min || l > max))
              {
                   System.out.print("Invalid dimesion");
                   System.exit(0);
              }
              else
              {
                   length = l;
                   width = w;
              }
         }
     
         Rectangle (int l, int w, Color c)
         {
              if((w < min || w > max) || (l < min || l > max))
              {
                   System.out.print("Invalid dimesion");
                   System.exit(0);
              }
              else
              {
                   length = l;
                   width = w;
                   color = c;
              }
         }
     
         int computeArea ()
         {
            return area = length * width;
         }
     
         void drawAt (Graphics g, int x, int y)
         {
              g.drawRect(x, y, length, width);
              g.setColor(color);
              g.fillRect(x, y, length, width);
              g.setColor(Color.black);
         }
     
         void setLength (int l)
         {
              length = l;
         }
     
         void setWidth (int w)
         {
              width = w;
         }
     
         int getLength ()
         {
             return length;
         }
     
         int getWidth ()
         {
             return width;
         }
     
         boolean equals(Rectangle rect)
         {
              if (rect.length == length && rect.width == width)
              {
                  return true;
              }
              else
              {
                   return false;
              }
         }
    }

    The instructor gave us a test class:

     
    class RectangleTest
    {
         public static void main(String a[])
         {
              Rectangle r1=new Rectangle(30,40);
              Rectangle r2=new Rectangle();
              Rectangle r5=new Rectangle(25);
              Rectangle r3=new Rectangle(35,20);
              Rectangle r4=new Rectangle(35,20);
     
              System.out.println(r1.computeArea()); //1200.
              System.out.println(r2.computeArea()); //100.0
              System.out.println(r2.getWidth()); //10.0
              System.out.println(r2.getLength()); //10.0
     
              r2.setWidth(20);
              r2.setLength(15);
     
              System.out.println(r2.computeArea()); //300.0
              System.out.println(r3.computeArea()); //700.0
              System.out.println(r4.computeArea()); //700.0
              System.out.println(r5.computeArea()); //625.0
              System.out.println(r1.ID); //1
              System.out.println(r3.ID); //4
     
              //r2.ID = 99; //will cause error
     
              System.out.println(r1.equals(r2)); //false
              System.out.println(r3.equals(r4)); //true
         }
    }

    I am trying to build my class around the restrictions implied by the method calls in the test class, so I'm wondering if there is a way to initialize each instance of a final variable without adding a parameter to the constructor.

  7. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Not sure what type of variable to use.

    Will randomly generated ID's work? If not, you can always use the hashCode() function to assign a more or less unique ID as long as you use the default Object class's hashCode() method.

    public final int ID;
     
    public Rectangle(int width, int height)
    {
         ID = hashCode();
         // other initialization
        ....
    }

    This is the reason the have encapsulation, because you could easily create a private member and only have a getter method to retrieve it's value, but never set it.

    // A better solution, but you're teacher/professor probably doesn't want you to use this yet
    private final int ID;
     
    public Rectangle(int width, int height)
    {
         ID = hashCode();
         // other initialization
        ...
    }
     
    public int getID()
    {
        return ID;
    }
    Last edited by helloworld922; July 9th, 2010 at 12:52 AM.

  8. #6
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Not sure what type of variable to use.

    Quote Originally Posted by helloworld922 View Post
    Will randomly generated ID's work? If not, you can always use the hashCode() function to assign a more or less unique ID as long as you use the default Object class's hashCode() method.

    public final int ID;
     
    public Rectangle(int width, int height)
    {
         ID = hashCode();
         // other initialization
        ....
    }

    This is the reason the have encapsulation, because you could easily create a private member and only have a getter method to retrieve it's value, but never set it.

    // A better solution, but you're teacher/professor probably doesn't want you to use this yet
    private final int ID;
     
    public Rectangle(int width, int height)
    {
         ID = hashCode();
         // other initialization
        ...
    }
     
    public int getID()
    {
        return ID;
    }
    I'm trying to as literal as I can in my interpretation of the assignment until I can get feedback from the instructor. That means that I was wondering if setting ID can be done without introducing into the code for Rectangle that is not explicitly written in RectangleTest. If this cannot be done, I will happily add more methods or parameters to Rectangle. I would just like to see it can be done with all of the restrictions I have set for myself in the absence of guidance from my instructor.

  9. #7
    Junior Member
    Join Date
    Oct 2009
    Posts
    9
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Not sure what type of variable to use.

    You just need a non-static final variable.

  10. #8
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Not sure what type of variable to use.

    Is there a way to intialize the final variable with each instantiation of class without having to add an argument to the constructor?

  11. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Not sure what type of variable to use.

    Would the variable get the same value for all instances? If not, where would it get the unique value from?

  12. #10
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Not sure what type of variable to use.

    Quote Originally Posted by Norm View Post
    Would the variable get the same value for all instances?
    No, it has to be different for each instance.

    Quote Originally Posted by Norm View Post
    If not, where would it get the unique value from?
    It would make sense that it would get the value from the constructor, but the constructor call in the pre-written test class is written as:

    Rectangle r1=new Rectangle(30,40);

    where a constructor with two arguments takes the length first and then the width; there is no other initializer. i was just seeing if I could possibly initialize the final variable without having to change the constructor calls in the test class.

    Is this possible?

  13. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Not sure what type of variable to use.

    Yes, you can assign the final variable a value in the constructor. How/where do you get the value?

    To get a unique value for each constructor, have a private static int that you increment each time you use it to assign a new value to the final variable.

  14. The Following User Says Thank You to Norm For This Useful Post:

    mjpam (July 13th, 2010)

  15. #12
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Not sure what type of variable to use.

    Alternatively, you can generate random numbers for the ID. However, do note that this method is not guaranteed to give you a unique ID every time.

    If you want a completely unique number, I believe the default object hashCode() method will do just fine since it gives you the object's memory address (and two different objects can't reside in the same memory spot).

  16. #13
    Member
    Join Date
    Jul 2010
    Posts
    45
    Thanks
    10
    Thanked 3 Times in 3 Posts

    Default Re: Not sure what type of variable to use.

    Unless if I am not understanding the question, it seems like the easiest way is to have a static variable that you increment in the constructor. How about something like this?

    class A {
     
    private static int currentID = 1;
    final int ID;
     
    public A () {
    ID = currentID++;
    }
     
    }
    Last edited by bbr201; July 13th, 2010 at 07:56 PM.

  17. #14
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Not sure what type of variable to use.

    mm, I think this is the easiest method but that method is very simple too

    public A(){
        ID = hashCode();
     
    }

    The only thing you have to be careful of is if you ever choose to override the hashCode() function (it will still work, but always generating a unique number will be impractical).

Similar Threads

  1. About heap data type
    By PaddyWangTheGG in forum Algorithms & Recursion
    Replies: 2
    Last Post: May 17th, 2010, 03:02 PM
  2. [SOLVED] Char type Comparisson
    By solo_2101 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 26th, 2010, 09:42 PM
  3. cannot be resolved to a type
    By Teraphim in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 16th, 2010, 10:42 AM
  4. unablissues wit type Date
    By cysquatch1 in forum Object Oriented Programming
    Replies: 2
    Last Post: December 21st, 2009, 12:20 PM
  5. Type casting error in Java
    By Eric in forum Java Theory & Questions
    Replies: 3
    Last Post: December 13th, 2008, 04:11 PM