rakesh kumar
rakesh kumar

Reputation: 97

the object reference is able to access the private data members direcly

public class College{ 
  int year; 
  String name; 
  College(int year,String name){ 
        year=year; 
        name=name; 
  } 

  public static void main(String[] args) { 
        College first=new College(1998,"BITS"); 
        System.out.println("The year is:"+first.year); 
        System.out.println("The name is:"+first.name); 
  } 
}

My output is: the year is 0 the name is null

how is this? According to me, the object first cannot access the private data members directly.

Upvotes: 0

Views: 204

Answers (4)

Alpesh Gediya
Alpesh Gediya

Reputation: 3794

In your question you mentioned, for below variables that they are private data members but that is not correct for your declaration.

   int year;  // default access specifier (for variable) is package not private  
   String name; /// default access specifier (for variable) is package not private

The default visibility is known as “package” (though you can't use this keyword), which means the field will be accessible from inside the same package to which the class belongs. See more information here.

You are shadowing variables in your code so you can fix them using below code

 College(int year,String name){ 
        this.year=year; 
        this.name=name; 
  } 

Upvotes: 1

BobTheBuilder
BobTheBuilder

Reputation: 19294

This happens because you're shadowing year and name fields inside your constructor.

Use either:

  College(int year,String name){ 
        this.year=year; 
        this.name=name; 
  } 

or:

  College(int y,String n){ 
        year=y; 
        name=n; 
  } 

I prefer the first option.

BTW, the fields aren't private as you didn't declare them as one and default is package. Even if you'd set them as private, static methods that belong to a class can see private member variables.

Upvotes: 6

Muhannad A.Alhariri
Muhannad A.Alhariri

Reputation: 3912

You must use

this.year = year 
this.name = name 

in constructor this will solve the problem :)

Upvotes: 1

Makoto
Makoto

Reputation: 106460

By declaring this:

year=year; 
name=name;

...you are shadowing your variables.

There is scope associated with your variables, and currently, the scope of both year and name is within the constructor. You're basically assigning it on top of itself.

You have a few options:

  • Use the this operator - this.year = year;
  • Rename the incoming variable names by prepending them with something:

    College (int theYear, String theName) {
        year = theYear;
        name = theName;
    }
    

Furthermore, there aren't any private fields within this class. They're all set up to be package-private, which is no visibility modifier at all.

If you had specified the fields year and name with the private modifier, then you'd be right; you'd have to use a getter to retrieve the variable values.

Upvotes: 5

Related Questions