Can anyone please explain what is 'public' and 'private' in oop and specifically in java?
I am a bit confused.
private methods can only be accessed by that class and not from another class.
public methods can be called from another class.
so you can have a public method being called which calls a private method.
you can have a private method call a public method.
but you cant call a private method from another class.
so what about public and private variables like private int x etc.?? same thing applies to them??
are they like global and local variables??
public and private variables are the same as methods.
global varibles are varibles that are going to be used in that class so diffrent methods might do diffrent things with that varible(eg add or subtract)
local varibles are varibles that are created inside a method and only used inside the method.
a local varible can not be accessed from out side the method.
just to confuse you.
you can also think of public and private varibles as global and local if u think about it ;)
It would probably be a mistake to think of "public"and "private" as relating in some way to the distinction between global and local scope. The notion suggests a bit of confusion about object-oriented programming. Public and private fields of a class are all "global" in that they can be called anywhere within that class. That class is a little program, and within it, any field can be read or written to. Within that class, there are local variables, these are declared within a method and only exist within a particular invocation of that method. So fields of the class are persistent: once you create an object -
Foo f = new Foo() - that object's fields will have a continuous lifecycle until you do something like
f=null; or otherwise dispose of it. If the class Foo has a method bar(), any declarations that happen within bar() cease to mean anything as soon as you return from that method.
So local variables are local variables and class fields are global variables.
Public and private just tell you who can access those variables - this is how you allow controlled interaction between classes. I haven't yet come across a really good reason to make a variable public, unless it's a constant, in which case it'll be declared static and final.
Methods should be private unless they have to be called by another class. Typically, I have an access point for any given action. That access point is a public method which then calls a bunch of private methods to do its work.
thank you people