Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Meet Objects Constructors

Using access modifiers while creating a new class object in Java

Why is it illegal to use an access modifier when creating a new object? Like this:

public GoKart newGoKart = new GoKart("red");

instead of:

GoKart newGoKart = new GoKart("red");

It isn't illegal. It is, however, illegal to use access modifiers on any variable inside a method.

2 Answers

Brandon Zeck
Brandon Zeck
3,127 Points

Sam Fisher, <p>

As Michael McDonald commented,</p><p> It is illegal to use access modifiers on any variable inside a method.</p><p> Access modifiers may be used to specify access of class variables such as data members and methods/functions.</p><p> Similarly, it can be used when creating objects too, as can be seen from the sample code below, but not within methods/functions.</p>

A.java

public class A
{
  private String mStr="";

  A(String str)
  {
    mStr = str;
  }

  public String getString()
  {
    return mStr;
  }
}

Introductions.java

import java.io.Console;

public class Introductions {
    static public A a = new A("Hello");

    public static void main(String[] args) {
        System.console().printf("Hi\n");
        // Welcome to the Introductions program!  Your code goes below here
        System.out.println(a.getString());
  }
}

Console

treehouse:~/workspace$ javac A.java && javac Introductions.java && java Introductions<p>

Hi</p><p>

Hello</p><p>

Hope this helps.</p><p> Please Up vote if it helps. </p><p> If you feel this is the answer that you were looking for, please `Mark as Answer'</p><p> And in case, it does not, please reply so that we will get to know.</p><p>

Thanks.</p>

mahesh gurbaxani
mahesh gurbaxani
1,420 Points

A follow up question on the above solution:

Suppose String mstr was public, then there should be no need for the getString() method. Then in the introductions class, can we print the string in the a object by using the command line a.str instead of a.getString().