public fields in abstract class? [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What should the accessablity of Fields in a Abstract Class be?
Is it bad practice to use public fields in abstract classes? The reason I'm asking this is because when I inherit from an abstract class I cannot access a private field from the subclass, the only way(s) around this as far as I can tell is to either make the field public, or create get/set methods to access the field... Which practice is best?

there are always protected fields

Best practice is to use getters and setters, possibly protected or public.
If using getters and setters seems like over kill because all your implementations will be developed with the abstract class itself in the same package or module, you can use protected fields. I don't think its best practice but a pragmatic choice.

In your case a protected member is propably the better choice as it will allow access to the member from within the class or any derived class.
As seen in this article on Member function visibility in Java programs.
Article, includes a nice table for different Java accessors and when/why to use them.

Related

A query regarding abstract class in java [duplicate]

This question already has answers here:
Is it possible to hide or lower access to Inherited Methods in Java?
(8 answers)
Closed 5 years ago.
I am writing a program where there are quite a lot number of methods in a particular class, so I decided to write an abstract class to help in keeping track of the methods.
Now, consider this: I have declared a method as abstract in the abstract class, and in the other class (which extends the abstract class), I want to override this method, but with access privilege reduced to private. Here, the compiler is giving a problem. It says that an attempt to assign weaker access privileges is being met with, which cannot be allowed. If I try to declare the method in the abstract class as protected (I have also changed the private ones to protected in the sub-class), it says that modifiers abstract and protected cannot be used together.
So, what can I do? Do I have to make the methods package access or public in both classes? If so, is there no way that I can declare these methods private?
Please note that I'm asking only for abstract classes, and not all classes in general.
What do you mean it can not be protected abstract - of course it can.
And the thing that you want to do is basically prohibited by the compiler and the language itself in the first place.
The answer to your question is: there's nothing you can do to reduce the visibility of a method declared in a parent class.
If you can restate what you're trying to accomplish by "keeping track of the methods" in an abstract parent class, you might get a different solution.

Omitting public modifier in java methods [duplicate]

This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 7 years ago.
I am learning Java and there's something bothering me and the textbook doesn't explain it.
I understand that you use modifiers to declare methods inside classes and all. But I suddenly got to a class declared like
static void(){
}
Why is there no public or private modifier and it still works? Can I avoid using the public modifier everywhere else or how does that work? I understand that static means member of the class and void that it doesn't return a value. Yet why not public or private for that matter.
For the sake of this explanation, the terms "functions" and "methods" are used interchangably. There is a small difference between them, for more information, ask Google.
Methods in Java that do not explicitly specify a modifier are by default package-private, so the method is visible to all the classes in the same package as the class where the method is declared.
Public functions are callable by all classes that have access to the class (i.e your whole project) and private methods are only callable within the class the method was written in. There is also the protected modifier, which specifies that the functions can only be accessed by the class, all its subclasses and classes in the same package.
"Why is that important?", you may ask. Good question!
You should use modifiers to hide methods/properties from other classes which may (ab)use them or in a bad case could lead to unexpected behaviour (not necessarily technically, but semantically... some methods just need a little more privacy just like we do). So a good place to start is private, which means only the class it is declared in is able to call it. More often than not, you'll need to give other classes access to methods, which is why the package-private, protected and public modifiers exist.
Data encapsulation is an important paradigm in programming, and these modifiers help you achieve just that.

Why instance variable in Java should be private if the Class has only getters and setters [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 8 years ago.
I had been asked the following question in an interview and i am curious to know the answer.
There are two classes as following,
public class EmployeeA{
public int empId;
}
public class EmployeeB{
private int empId;
public void setEmpId(int empId){this.empId = empId;}
public int getEmpId(){return empId;}
}
There are two classes where one class has a public instance field and other have a private field with getters and setters. In this case, which is better implementation and why?
[I have learned that making instance variable private is the better idea. But in both cases i can modify the value of empId attribute. ]
The one-word answer they're probably looking for is "encapsulation".
By encapsulating the private field value, you have the opportunity to change the logic on how the value is set/retrieved in the future. Say, for example, you want to validate on set and filter on retrieval (get). By encapsulating the value, your creating an API which allows for better maintenance moving forward.
Maybe a bit off-topic, although people usually talk about "encapsulation" when talking about "getter/setter", "getter/setters" are actually still far from proper encapsulation.
This famous "why getter and setter methods are evil" is something worth to read. When we say getters and setters are evil, it doesn't mean that we should expose variable directly. It is about further hiding internal data by providing meaningful behavior in class, instead of providing accessors for properties. Although there are a lot of cases we still need accessors, this is something that worth giving attention when you are designing.
Going back to your question, if it is me, I will answer: providing getters and setters provides a minimal level of encapsulation and allow us to do extra work or derives data when we are setting and getting properties. However, for a proper encapsulation, I would rather design the Employee class to provide proper behaviors, instead of simply acting as a value object which only provides bunch of getters/setters.
The accesssor (getter) and mutator (setter) are JavaBean requirement but not all classes in Java must follow this design pattern. Why not creating this class as immutable by having a constructor that take the id (or even better, a static factory). You can then provide an accessor for the the id. That is generally not a good idea to be able to change the id of an object, if the id is used in a Map as the key and you change it, good luck to retrieve you object... Make the class immutable solve this kind of problem.

private access modifier and protected access modifier [duplicate]

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.

Model class properties should private or public? [duplicate]

This question already has answers here:
Why Not Use Public Member Functions
(3 answers)
Closed 9 years ago.
I have question which has been going around in my mind since long.
My Model class should have properties private or public? (Below code is written in PHP but question applies in general for any language)
class Xyz extends Model {
public function __call() {
}
public $description;
public $title;
}
In above example I have public properties $description and $title. Should I make them private?
I update my model as follows
$x = new Xyz();
$x->title('Hello');
$x->description('Blah blah');
$x->save();
I can update and get them by using magic method __call. So why do we need to keep them public? I can make them private. But as I see all the frameworks around keep model properties public.
Any thoughts?
UPDATE:
In answers, everyone is saying follow encapsulation and use private methods. Good but no one has the answer why some PHP frameworks have model properties public ? There should be some reason, isn't it?
As per OOP, we need to follow encapsulation. Please make your properties private and have public accessors and mutators. but, it depends that your accessors and mutators can have other modifiers as well. But, The properties should be always private.
Class fields should always be private. Getters and setters for the fields should be public. Aside from being standard, it is also good to have it this way so that you have the control to do what ever you want to the values that the client classes wants to set to you private fields.
For example, if you want to persist an object to a database, and one column is stated to be not null, and you are not sure if your client class will really return a non-null value, you can handle the null check inside the setter so that the values that you are about to persist to the db contains no null field, as what the table of your db demands.
The fields should always be private as per OOP encapsulation principle. Now the thing is with the getter and setter accessor methods.
The getter is usually safe to make it public. The only downside of it is that you will have to maintain backward compatibility between versions, as this will be part of the public contract of the class. So if the field is something that is part of the implementation rather than interface, than maybe you want to keep it protected.
As for the setter the better question is if to create one or not. If you want to keep your class immutable (or at least some parts of it) with all the advantages and disadvantages that comes from it, then you'll not be creating a setter at all.
You have to make all properties as private in model class and if you have to encapsulate their value then you have to use appropriate getters and setters to get and set their values.

Categories