0

I am still fairly new to java, so please bear with me.

I am having trouble understanding why it is that I can only access certain methods / functions that belong to an instance of an object from certain classes / places/. Once I create an instance of an object and then press the dot "." operator it does not bring up all the methods that I want to use for it, (I want to see all the methods that the objects class inherits and implements.)

For example:

    // In a junit test class, I make an instance of the class DailyLog which takes 2 
    // integers   
    private DailyLog log; // which seems fine for now, but when I add on the next
    // line:                         
    log = new DailyLog (5,500); // It gives me an error on the semicolon on the line 
    // above  saying "-  Syntax error on token ";", , expected"

I do not understand why it will not let me create an instance of DailyLog and set it's paramaters...?

Question 2: If I just leave the first line of code in, then set the parameters of log within a method in the same class, it lets me set it's parameters, but when I press the "." operator, It does not show me the size function, which is the function I want to use. - I thought it would inherit size from a superclass, so why does it not let me use it?

Question 3: I have a method within the dailyLog class called variance, and another called numInsertions, I need to use the numInsertions method within the variance method, but when I write below, the only way I can get to the numInsertions method is through another method, and this will not work as i need to access the numInsertions method to directly to assign it's value to b, not through another method as this will change it's value.

      public Integer variance() throws SimulationException{
          Integer a = log.    

I think it might have to do with scope, when I have another class which creates an instance of dailyLog, and when I press the ". operator on it, it gives some methods to use from the daulyLog class and it's superclass, but not all of them. I find this quite confusing, and help would be appreciated, thanks.

UPDATE**

Maybe putting more code here will help to illustrate my problem:

public class dailyLog implements Log{

private Integer userLogSize1;
private Integer maxEnt;
private ArrayList<Integer> log = new ArrayList<Integer>();

public dailyLog (Integer userLogSize, Integer maxEntry) throws SimulationException{
    if ((userLogSize<= 0 || maxEntry <= 0)){
        throw new SimulationException("message goes here");}
        this.log = new ArrayList<Integer>(userLogSize);
        for (Integer i = 0; i <= userLogSize; i++){
            log.add(null);}
        userLogSize1= userLogSize;
        maxEnt = maxEntry;
    }

public Integer numInsertions(){
       Integer total = 0;
    for (Integer i = 0; i < log.size(); i++){           
         if (log.get(i) != null){
            total++;}}
    return total;}

//  *** below I want to write log.numentries but i cannot, why it this? I can only write
// log.get(numentries()) but that gives the wrong answer.


public Integer variance() throws SimulationException{
    if (log.size() == 0){
        throw new SimulationException ("Put message here");}
    Integer a = log.get(0);
    Integer b;
    Integer d = log.get(1);
    if (d == null){
        b = log.get(numInsertions()-1);}        
    else {b = log.get(numInsertions()-2);}
    Integer c = log.get(userLogSize1-1);
    if ( c == null){
        return a - b;}
        return a-c;}
}
  • Just in case, you can't see functions declared as 'private' from outside. Try 'public'. Read more: http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private – fersarr Mar 30 '14 at 05:17

3 Answers3

0

I think you are seeing the different protection levels in Java. For the members and methods of a class, there are generally four protection levels: private, public, protected, package-private. If a method or object is not prefixed with one the keywords private, public, protected, then it is by default package-private.

A method or class member which is private can only be referenced within the same class in which it is declared.

A method or class member which is public can only be referenced from any class in any package.

A method or class member which is protected can only be referenced from the same class and subclasses.

A method or class member which is package-private can only be referenced from within the same package. If you are developing with the default package (that is, you have not declared a package), then your code will generally treat package-private exactly as it would treat public, since all classes are defaulted to the default package.

Here is a reference and here is another question which explains the same ideas in less words.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

if you're trying to pass a method from one class to the other, and you don't want to make it static, meaning it would be shared across all instances, you can create a new instance of the class in a different class. For example say you have class A and class B:

public class A {
private int a;
private void setA(int a) {
    this.a = d;

and class B:

public class B {
private int b;
private void setB(int b) {
    this.b = b;

so then I can call all of class A's methods by invoking a constructor from it:

public class B {
///Constructor line
private A a = new A();
A.setA(10);
System.out.println(A.a);   ///should print 10
Snoop Dogg
  • 62
  • 3
  • Thanks, I fully understand this above, but am still unable to determine why I cannot access the numInsertions method directly from the variance method. – user1319364 Mar 30 '14 at 06:51
0

You need to understand modifiers (i.e. private, public, protected, and package-level). Every field of a class and method of a class (both static and non-static) has a modifier. If you don't specify one, then it is "package-level". You don't specify modifiers inside a code block (e.g. a method body) because it is assumed that the scope of such variables is the inside block. Just a quick example of a block-scope, the following is legal in Java:

public int foo(){
    {
        int max = 0;
        for(int i = 0; i < 10; ++i)
            if(i > max)
                max = i;
    }
    final int max = -10;
    return max;
}

In a nutshell you have the following (note that constructors would be considered methods in the following):

  • public: Anything can access this method or field. For fields, this means any class can set this field unless it's declared final. You should be very aware though that even an object declared final can be modified (such as an array or any other mutable object). For methods, this simply means any class can call this method.
  • private: Only this class can access this field or method. This means that the only place you can modify these fields or call these methods is within this class file. An instance of this class can access fields from another instance of this class (through some method written inside this class's body that references some other object instance of this class).
  • protected: Any class that is either in the same package as this class or a subclass of this class (could be in a separate package) has direct access to a protected field or method.
  • package-level: To specify package-level access, you do not specify any modifier at all (i.e. public, private, or protected...nothing). In this case, any class within this package has access to this field or method.

The better question is when should you use which? Most methods should be public and most fields should be private as a general rule. You should be very weary of people who claim that these things are for "security". The only way to ensure data integrity of an object is to only return primitive values or immutable objects or copies of mutable objects. As a quick example, let's say you implement an ArrayList (a dynamic array). Internally, you probably have an array object such as private int[] arr. If you return this array object in any public method then you run the risk of the calling class modifying the internal array and making your ArrayList inconsistent.

I would follow these guidelines:

Fields

  • public: Only declare a field public if it is also final and an immutable object or primitive. This should be used for persistent objects who's field never changes (i.e. once it's set in the constructor this public final field will never be changed).
  • protected: This should primarily be used in abstract classes. That is the abstract class declared a data structure which its subclasses can use and reference (and modify). If this is something like a list it may still be appropriate to declare it final (that is something the sub-class can modify, but not reassign).
  • package-level: This should primarily be used by auxiliary classes in a package. They generally shouldn't be final (although if they are things like a list that may be appropriate). As a quick example. If you implement a heap, you may want the heap nodes to hold information about what element they are storing and where they are in they heap's array. The heap is really responsible for setting this, so by declaring it package level, your heap implementation can directly access and reassign things like the heap index and heap value for each of its heap nodes.
  • private: Private fields are most common. Most fields should be private. This means that only methods in this class file can modify or reassign this field. This should be used when you want to guarantee the behavior of a class. If you use any other modifiers, then the behavior of this class's data may be dictated by other classes.

As for methods, it's pretty simple. A public method should be something that any class can call to query the object without disrupting the data integrity of the object (i.e. the method should not be capable of putting the object into an inconsistent state which means public methods should not, in general, return mutable fields). Private, protected, and package-level methods should all be helper methods which are used to improve modularity. Basically it depends on "who" you trust. If the method is private then you only trust this class to call it correctly. If it's package level, then you only trust classes in this package to call the method correctly. And finally if it's protected, then you only trust classes in this package and sub-classes to call this method correctly.

Jared
  • 940
  • 5
  • 9
  • Thanks Jared, I understand the modifiers well enough, which is why i find this problem so puzzling/ All my methods are public. A class from outside it is able to create an instance of it and call it's methods. but when I try to call the numInsertions method from the variance method I cannot. there must be a way to surely? – user1319364 Mar 30 '14 at 06:55