Originally posted by scracker
Hi
Can we access private variables?
only within the same set of curly brackets
Code:
import java.awt.*;
public class Professors{
private String name;
private int age;
public Professors(String n, int a){
name = n;
age = a;
}
public boolean olderThan(Professors a){
return (age > a.age);
}
}
How come in this code we can do that?
access is based on classes, not objects. all object instances of Professors can access each others private variables. try this:
Code:
import java.awt.*;
public class Professors{
private String name;
private int age;
public Professors(String n, int a){
name = n;
age = a;
}
public boolean olderThan(Professors a){
return (age > a.age);
}
public static void main(String[] argv){
Professors p1,p2;
p1 = new Professors("bob", 10);
p2 = new Professors("nob", 20);
System.out.print(p1.olderThan(p2));
System.out.print(p1.age);
}
}
class test{
int i;
public test(Professors p){
i = p.age;
}
}
I remember my instructor said that to access a private instance variable, we need to write a get method to do that. Is that correct ?
yes, because it allows you to control the access to the data.. maybe the data is in some raw format and needs making nice before it is given out..
Bookmarks