hello I am currently studying for a programming exam in java and I would like to understand the difference between a static method and a protected one. thanks in advance
Those two are different concepts.
static defines whether a field or method belongs to the class or its instances.
protected influences the visibility of a field or method. When a field or method is set to protected visibility, only classes inheriting from this class can access the field or method.
Notice that those two keywords are orthogonal: a field or method could be decorated with static and protected simultaneously.
Since you seem a newbie to java language, in a nutshell:
protected: An Access modifier(member variables + methods). You can find a whole lot of explanation over the internet.
static: NOT-An-Access modifier(blocks, variables,methods, nested classes)
You might want to check SIB/IIB (static and instance Initialization Blocks for a clear concept of static)
Static classes and protected classes can coexist for a single variable, so they are very different things. If you don't have a good grasp on Object Oriented programming, I highly recommend finding tutorials on YouTube, as there are some really good ones! :)
Static Variables
Are variables that belong to the class, not each individual object that the class creates. This means that if the variables is changed, it changes for everything.
Protected Variables
Are variables that are only accessible to it's child classes. A child class will have the variable, but no other classes will have access to it. If you know the difference between public variables and private variables, protected is kind of like a middle ground.
This is a tutorial series I recommend to learn more. https://www.youtube.com/playlist?list=PLAF3anQEEkzQPQv3FAhIuSWrepTayQJpL
Related
Should the instance variables be private or protected in java abstract class?
Simple question. I am trying to get more insight into the concept of abstraction in java.
Thanks!
As a rule of thumb, go for non-final private variables. If your design calls for giving derived classes access to these variables, provide protected methods for accessing them.
Using protected variables creates maintenance liability in all classes, abstract or not. As soon as someone inherits from your abstract class, your protected variables become exposed as if they were public. Here are some reasons why this variables should be avoided:
Inheriting classes can change your variables at will - this may go around variable validations set up by the abstract base class
Inheriting classes become dependent on variable names and types - this locks in the design choice that you made when defining protected variables.
First rule does not apply to final variables because they cannot be changed, so the rule makes an exception for them. Second rule still applies, though, so you should be careful about defining protected variables, even in situations when they are final.
If protected then this class and any subclasses may access the property. If private then only this class may access the property (it is not inherited). It depends on if you need to access them in any subclass.
This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 8 years ago.
I have a problem understanding access modifiers in Java.
public: can be used anywhere.
private: can only be used inside the same class.
protected: can only be used in subclasses.
I saw many examples and tried but I couldn't understand.
I know only the definition. Please any one help me one this give me more examples.
What kind of programs would use private?
What kind of programs would use protected?
What kind of programs would use public?
This is very basic in OOP concepts. When the class should need to not to expose it parameters, it would define them as "private". Any class outside have no any access to it. Either these variables are for the use of the class itself only or there are public getters and setters which give indirect but controlled access to these variables.
example is age. Let say someone need to set minus value to age, then the setter method can avoid setting that value. It is a bad practice in OOP to expose variables as public. If you do that, any other logic which can create an instance of the class can change the value of the varible.
The variables are marked "protected" when we need to allow sub classes too can use or have access to these variables.
Mostly public access modifier is used for methods
You would use all three in all kinds of programs, except for very simple programs where everything is typically public.
A good practice is to use the most restrictive access modifier that you can. Access modifiers exist to help you stop yourself from making mistakes - they are not actually required per se, but they are very useful. If you're writing a library for other people to use (which you aren't, but you might in the future) they also stop other people doing weird things with your code.
Usually, a class is related to one thing (e.g. a book in a library). If you are writing a library system, you might have a class like this:
public class Book
{
private String title;
public String getTitle() {return title;}
public Book(String t) {title = t;}
...
}
Notice that title is private, so you can't directly get or set the title of a Book. You can indirectly get it using the getTitle method, which is public. You can only set it once, when the Book is created.
Code inside the Book class can still set the title, so this is not foolproof. final would be better for that, but this is to demonstrate access modifiers, not final.
You could just make title public, and say that you won't change the title of a book, but later you might do it by mistake. Again, access modifiers help you prevent yourself (and sometimes other people) making mistakes.
Edit: Also, you're wrong about protected. protected things are accessible to subclasses or classes in the same package. There's also a default access modifier, which has no keyword, which you get if you don't use public, protected or private. The default access modifier makes things accessible to the same package only.
private is used when you have variables or methods in a class which you will not use outside the class.
public is used for variables and methods which need to be accessed outside this class.
protected is used when the variables need to be used only that class and in its child class.
here is a good example.
I know the difference between static type and other types but I am not sure which is to used where. Now I am using static types in all places to avoid object instantiation. Is it a good idea to use it that way ? Is there any particular disadvantage in using static type in all places ??
EDIT
What do you call this as static String staff ?
This is an excellent question. Usually you should not use static methods/variables unless you know for sure that it's a correct application for it. In object oriented programming (OOP), objects encapsulate data and behavior. Typically, *instance methods are used to manipulate the object's data.
Static methods/variables should only be used for functionality that is not associated with any particular object. A good example of a valid application for static is Math.random().
Some notes about instance and static methods/variables:
Instance variables have access to static and instance variables/methods, but static methods can only access other static variables/methods.
A static variable will always be the same across all instances of a class.
A good book to read that covers this topic is Clean Code by Robert Martin. Highly recommended.
*instance methods are the opposite of static methods. They are associated with a class instance, instead of the class itself.
Addressing your edit, assuming that that's a variable, you'd access it like this:
MyClass.staff = "bob, george, and linda";
System.out.println(MyClass.staff);
Edit: here's a post I made on another forum a while back, with some good answers. It's a PHP forum, but the concepts still apply.
http://forums.devnetwork.net/viewtopic.php?f=1&t=127667
When there are multiple instances of an object, static-typed variables and functions are shared across all instances.
Most logic in any application will be modularized, and will operate on some shared fields. This is the reason why most methods are non-static. The 'fields' in this case can be something as basic as 'firstName', etc. But in other cases, the 'fields' are instances of other classes such as DataAccess (DAO) classes.
Variables i.e. fields should almost never be static, unless they are 'constants'.
A good example where you will be use static methods is a class that transforms Strings, for example:
public class StringUtil{
public static String convertToHex(String orig){
}
}
I want to know what way is more efficient.
No global variables, passing variables through parameters, having all methods static
No global variables, having only main method static and creating class object in main to access methods
Use only global variables, having only main method static and creating class object in main to access methods
I am currently using method 3 but I want to know what is more efficient. This class will not be used by any other class outside of it, it pretty much stands alone.
Example of my code structure:
public class myClass {
private int globalVariable;
public static void main(String args[]) {
myClass c;
c.someMethod(); // Changes global variable from method
System.out.println(someMethod); // Prints solution
}
public void someMethod() {...}
}
No class is an island.
There are no silver-bullets, at least its very true in programming.
Premature optimisation is the root of all evil.
In Java we don't have global variables. We only have class variables, instance variables, and method variables.
[Edit]
I am trying to explain here my last point. In fact, bringing the discussion, that is going-on in comments below, to the actual post.
First look at this, an SO thread of C#. There folks are also suggesting the same thing, which is,
There are no global variables in C#". A variable is always locally-scoped. The fundamental unit of code is the class, and within a class you have fields, methods, and properties
I would personally recommend erasing the phrase "global variable" from your vocabulary (this is in the comment section of the original question)
So, here we go.
retort: Classes are globally scoped, and thus all class variables are globally scoped. Hence should be called global.
counter-retort: Not all classes are globally scoped. A class can be package-private. Therefore, the static variables in there will not be visible outside the package. Hence, should not be called as global. Furthermore, classes can be nested, thus can be private as well and definitely can have some static variables but those wouldn't be called global.
retort: public classes are globally scoped, and thus all class variables are globally scoped.
counter-retort: Not exactly. I would like to move the previous argument here but on a variable level. No matter if the class itself is public. The variables in there can be protected, package-private and private. Hence, static variables will not be global in that case.
Now, if you like to call public static variable in public static class, as global then call it by any means. But consider this, when you create a new ClassLoader (as a child of the bootstrap ClassLoader) and load a class that you've already loaded. Then that results in a "very new copy of the class" -- complete with its own new set of statics. Very "un-global", indeed. However, we don't use the word global in Java because it tends to confuse the things and then we need to come with whole lot of explanations just to make everything clear. Folks rightly like to explain the feature of global variables in Java by static variables. There is no problem in that. If you have some problem/code in any other language and that is using global variables and you need to convert that code to Java, then you most likely make use of static variable as an alternative.
A couple of examples I like to render here
When I started Java, instructors like to explain the difference of passing object type variable and primitive variables. And they constantly use the term objects are pass-by-reference, whereas primitives are pass-by-value. Students found this explanation quite confusing. So, we came up with the notion that everything in Java is pass-by-value. And we explain that for objects references are pass-by-value. It becomes much more clear and simple.
Similarly, there are languages which support multiple-inheritance. But Java doesn't, again arguably speaking. But folks tend to explain that feature using interfaces. They explain it by class implementing many interfaces, and call it multiple-inheritance. That's perfectly fine. But what the class, actually, receives by inheriting a number of interfaces. Frankly speaking, nothing. Why?
. Because all the variables in interfaces are implicitly public, final and static, which apparently means those belongs to the class and anyone can access those. Now we can say that perhaps there would be some inner class in the interface, then the class implementing the interface will have it. But again that will be static implicitly and will belong to the interface. Therefore, all what the class will get are methods. And don't forget just the definition and the contract which says, "the class implementing this interface must provide the implementation of all methods or declare itself abstract". Hence, that class will only get responsibilities and nothing much. But that solves our problems in a brilliant way.
Bottom line
Therefore, we say
There are no global variables in Java
Java doesn't support multiple-inheritance, but something like that can be achieved by implementing multiple interfaces. And that really works
There is nothing pass-by-reference in Java, but references are pass-by-value
Now I like to site few more places
Java does not support global, universally accessible variables. You can get the same sorts of effects with classes that have static variables [Ref]
However, extern in ObjectiveC is not an alternative to a class-scoped static variable in Java, in fact it is more like a global variable … so use with caution. [Ref]
In place of global variables as in C/C++, Java allows variables in a class to be declared static [Ref]
Furthermore, the overuse of static members can lead to problems similar to those experienced in languages like C and C++ that support global variables and global functions. [Ref]
All these are inferring one and the same idea. Which is Java doesn't support global variables.
Hell, I wrote that much. Sorry folks.
Performance doesn't matter. You want it as easy to read as possible.
I would do 2 as much as you can. When you really need constants and statics, make constants and statics.
For example, a null safe trim makes a good static method. New upping a StringTrimmer is silly. Putting if null then x else z in 1000 others is silly.
I think this was settled back in 1956 and 1958, when people invented Lisp and ALGOL58 and pondered about modularity, referential transparency, and sound code structure as means to tackle impenetrable spaghetti code that rely on global variables (and who tend to exhibit the software equivalent of the Heisenberg uncertainty principle.)
I mean seriously, this is 2011 and we still wonder about whether to use global variables over encapsulated fields or parameter passing for quote-n-quote efficiency. I mean, seriously.
I may sound arrogant (so be it), but I'll say this:
I can understand some spaces where you have to make some sort of global variable trade-offs (.ie. very resource constrained embedded platforms, for example). I can understand if a person that is just starting in CS (say a freshman) asks this.
But if someone beyond freshman level (let alone someone that does coding for a living and not coding in the most resource barren of environments) asks or even remotely thinks about this as an acceptable thing to do should seriously reconsider going back to the basics (or reconsider this profession - we have too much craptacular code already.)
Short and concise answer: No, it makes no sense. There are no noticeable games. It is not worth it. It leads to craptacular code. And all of these have been known for 50 years now.
I'm working my way through an exercise to understand Java, and basically I need to merge the functionality of two classes into one app.
I'm stuck on one area though - the referencing of objects across classes.
What I have done is set up a gui in one class (test1), and this has a textfield in ie.
chatLine = new JTextField();
in another class(test2), I was planning on leaving all the functionality in there and referencing the various gui elements set up in test1 - like this test1.chatLine
I understand this level of referencing, I tested this by setting up a test method in the test2 class
public static void testpass() {
test1.testfield.setText("hello");
}
I'm trying to understand how to implement the more complex functionality in test2 class though, specifically this existing code;
test1.chatLine.addActionListener(new ActionAdapter() {
public void actionPerformed(ActionEvent e) {
String s = Game.chatLine.getText();
if (!s.equals("")) {
appendToChatBox("OUTGOING: " + s + "\n");
Game.chatLine.selectAll();
// Send the string
sendString(s);
}
}
});
This is the bit I'm stuck on, if I should be able to do this - as it's failing on the compile, can I add the actionadapter stuff to the gui element thats sat in test1, but do this from test2 - I'm wondering if I'm trying to do something that's not possible.
Hope this makes sense, I'm pretty confused over this - I'm trying to understand how the scope and referencing works.
Ideally what i'm trying to achieve is one class that has all the main stuff in, the gui etc, then all the related functionality in the other class, and target the first class's gui elements with the results etc.
Any thoughts greatly appreciated.
If you can access chatLine in the first place, you can call its (public) methods, including addActionListener. To access chatLine directly, you need to make it public, and if you want to make it specific to the class (as opposed to a different chatLine for each instance of the class), it needs to be static.
Note, however, that it's often desirable to not make variables public. An important reason for having classes and objects in the first place is encapsulation. You might consider hiding the implementation inside the classes by making it private and only providing higher level public methods to access what is needed, e.g. do not expose the "raw" JTextField but rather expose the functionality you use it to provide.
I'm not clear on whether chatLine is a local variable, an instance variable, or a static variable. Any of these things could be the source of your compile error, which you didn't specify -- what's the error?
If it's an instance or static variable, it can be made visible from anywhere by making it public. This doesn't mean that's a good idea.
At least, it should be private and exposed via a getChatLine() method.
Even then, there's some question about whether this design is the right one, but at least you'd be doing it right at a compiler level and basic data encapsulation level.
Generally speaking everything in Java is referenced but primitive types.
The so called visibility of objects is another matter:
public scoped members are visible
to all
'Package Friendly' members (those
that have no scope explicitly
mentioned) are visible to all abjects
belonging to the same package
protected scoped members are both
'Package Friendly' and visible to all
inheriting class objects
Finally, private scoped members are
visible only to the object itself
[Objects from the same class can view
each other's private members (as far
as I can recall)]
Now,
an inner static class can access its
enclosing class's static members.
A 'normal' inner class (without the
static modifier) can access its
enclosing class's static members
and enclosing object's instance
members - that goes as well to
anonymous inner class.
Finally any chain of method/field calls as below is valid (but ugly) as long as no part of the chain 'references' a null:
myObj.getThatObject().somePublicField.doSomthing().activate().someOtherPublicField
One recommendation though is not to declare members as public...