Methods and variables

DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: Methods and variables

  1. #1
    Join Date
    Aug 2002

    Methods and variables

    Being new at java, I have this question. Methods and variables that are associated with a class rather than with instances are declared private. Is this correct?

  2. #2
    Join Date
    Aug 2002
    I may be wrong but I believe that methods and variables that are associated with a class are called static, rather than private. You can declare either static or non-static members private if you need to restrict them from being accessed by anything outside of the class they were declared in.

  3. #3
    Join Date
    Aug 2002
    First about static part:

    Any variable declared static will have same value throughout all the instances of that class e.g

    public class family{
    String first_name;
    static String family_name="Mathur";
    int age;
    String gender;

    if we create instances of this class say :
    family father-new family();
    family son-new family();

    then father.first_name & son.first_name can have different values but both the instances of family class will have common value for variable "family_name" or in other words if you change the value of family_name to say "Wilkes" then it will change for all its instances.

    Second part is :
    Protected, private & public are the acess control levels (deault is public) and have following implications:

    Private: the method/variable cannot be seen or used by any other class unless called through an internal function of same class.

    Protected: the method can only be called from subclasses or classes within same package.

    Public: allows any class to acess and manipulate value of this variable.


  4. #4
    Join Date
    Sep 2002
    I think your description of static is good, but missing one important point.

    If you declare a member variable or method static, you can access those items without having to create an object. So, if you make a really cool class for printing your name 10 times to the screen, such as:

    public class ReallyCoolNameClass
        static void printName(String name)   
            for(int i = 0; i <=10; i++)
    You can use this in your code like this:

    Instead of having to do this:

    ReallyCoolNameClass name = new ReallyCoolNameClass();
    This is probably a dumb and bad example, but hopefully it gets the point across.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center