• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Access Modifiers

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Folks,
Can anybody explain me why the following line in the code is Illegal?
class Complex {
private double real, imaginary;
public Complex (double r, double i) { real = r; imaginary = i;}
public Complex add (Complex c) {
return new Complex (real + c.real, imaginary + c.imaginary);
}
}
class Client {
void useThem () {
Complex c1 = new Complex (1,2);
Complex c2 = new Complex (3,4);
Complex c3 = c1.add(c2);
double d = c3.real; // Illegal!
}
}
what I don't understand is that c3 is an instance of class complex and we can have access to a private member of a class through an instance of that.What is difference between c3 and c1 and c2?
Thanks,
Samira
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Complex {
private double real, imaginary;
public Complex (double r, double i) { real = r; imaginary = i;}
public Complex add (Complex c) {
return new Complex (real + c.real, imaginary + c.imaginary);
}
}
class Client {
void useThem () {
Complex c1 = new Complex (1,2);
Complex c2 = new Complex (3,4);
Complex c3 = c1.add(c2);
double d = c3.real; // Illegal!
}
}
Although c3 is an instance of complex but private variables can't be acessed outside the class.real is private variable thatwhy it can't be accessed in other class client
 
I didn't like the taste of tongue and it didn't like the taste of me. I will now try this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic