-2

Suppose I have a function in Java.

public function goodname(int a){
    int b=8;
}

Is there any way to access variable b without getter and setter?
I was asked this question in an interview. My answer was NO but he insisted that there is a way i am wondering how can i do this?

Zulfiqar Tariq
  • 394
  • 3
  • 14
  • 3
    Hopefully in the interview the code would at least compile? – T.J. Crowder Oct 16 '17 at 07:21
  • 1
    Java doesn't have functions. Only methods. – Ivar Oct 16 '17 at 07:21
  • Quoting the dup question: *1) Any variable declared in a method is only visible in that method. (method-local). The programmer has no choice in that.* – GhostCat Oct 16 '17 at 07:23
  • 1
    @GhostCat: Other possible dupe: https://stackoverflow.com/questions/9351955/how-to-use-a-variable-of-one-method-in-another-method – Ivar Oct 16 '17 at 07:24
  • I think you mean `javascript` rather than `java`. These are two [completely different languages](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java), but often confused. I suggested an edit to your question. – Filnor Oct 16 '17 at 07:24
  • @chade_ You can't declare integers in JavaScript. – Ivar Oct 16 '17 at 07:24
  • 1
    @Ivar Thanks. I updated the dup request. Now I almost hope some more downvotes come in so we can delete this thing here. – GhostCat Oct 16 '17 at 07:54

3 Answers3

3

No, b is entirely private to the goodname method. It cannot be accessed by code outside goodname unless it's exposed in some way by code within it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

No, this b only exists while goodname is being executed. You can't access it from outside.

Herr Derb
  • 4,977
  • 5
  • 34
  • 62
-1

There is no way to access the inner variable. You can't access it from outside. Unless you make it like below

public int b=8;

public function goodname(int a){
//b = 8;
}
Zeeshan Sardar
  • 235
  • 3
  • 15
  • 1
    "Make it generic" ... so the answer that uses the "most wrong" language gets the accept. You didn't even take the time to fix the wrong syntax. – GhostCat Oct 16 '17 at 07:53