OOP and inheritance of private fields [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In C# the spec says:
Instance constructors, destructors, and static constructors are not
inherited, but all other members are, regardless of their declared
accessibility (§3.5). However, depending on their declared
accessibility, inherited members might not be accessible in a derived
class.
so private fields are inherited into a derived class but they are not accessible.
However the Java spec says:
Only members of a class that are declared protected or public are
inherited by subclasses declared in a package other than the one in
which the class is declared.
so private fields are not inherited into a derived class.
And what does explain the OOP theory? Is correct C# or Java designers?
A bit confused on this aspect.
P.S.
I haven't C++ experience? What does C++ designers says on this?

Well, the C# version is more-clear because even in Java, private fields will be available as part of the child object but they will no be directly accessible unless you have a public getter in the parent class to get its value.
You can actually use reflection to make private fields (of the parent ) accessible and read their values directly.

Keeping the things simple and clean, taking some part of quote you mentioned for c++
However, depending on their declared accessibility, inherited members might not be accessible in a derived class.
The same thing happens in Java as well. You can't access private fields in Java too.
There are methods around them to access which is another story (encapsulation)

Answering at least the C#/Java-part as I don´t know much on C++.
However, depending on their declared accessibility, inherited members might not be accessible in a derived class.
The C#-spec seems to be a bit more meaningful, although Java handles private mebers the same way. The private members from base-class also exist in Java (however they are not inherited, see are private fields inherited in Java?). As you cannot access them this is not usefull anyway. The internals however are of course initialized by setting the private members also. So instances of your derived class of course have all the private members of the base-class, inheritance however means any kind of polymorphism which implies you might be able to override (assuming your member is not static or final/selead) them which makes no sense at private members.
So coming to the chase there should be no need for accessing the internals at all, neither in C# nor in Java nor anywhere else. Simply assume your derived instances get all the base-members fully-initialized and do your actual work.
Relating to what you call "OOP-theory" I doubt there is a cleaner answer as for this principle (which is implemented in different ways in the mentioned languages)private members have no relevance at all. OOP merely handles the interactions between objects with their surrounding not their actual internals.

I think the confusion is related to a confusing wording. In Java or C# or any other OO language, if you construct a child you have to call the parent constructor, because the parent is part of the child. Very often the call of the parent constructor is done implicitly.
So the private attributes from the parent are always present somewhere within the child object. Then OOP ensures, that you can not access the private attributes within the child. This encapsulation is the important point. And this fact is described by the two references: Either you call it the attributes are not inherited or you say that they are inherited but not visible.
As mentioned above you can (ab)use the reflection library to get around these restriction.

Related

Clarification of the meaning and functionality of private and public in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I have seen this question and I understand what theoretically the difference between public and private means. My understanding is as follows:
public means that it's "visible" / "accessible" everywhere. As in every class can see it.
private is only "visible" / "accessible" in its declared class.
My first question is:
What does "visible" exactly mean? I'm not quite sure how to interpret the meaning of "this class can't "see" this method".
Second question is:
What is the functionality/use of these? In the second asnwer of the question, he explains that if we "encapsulate" our code, then we will make it "easier for ourselves to change the code later and not break anybody's else's code". What does this exactly mean?
Examples would help a lot
With respect to the first question: What does "visible" exactly mean?
visibility translates to accessibility when talking of classes, whenever a class is declared public, that class is accessible to all the other classes of the project, and all the classes can access them as they like either by inheriting the class or instantiating a new object of the class. Similar concepts also transcend to public class members. However, one important point is that public class members such as methods and variables will only be visible/accessible to other classes if the containing class is not marked as private.
On the other hand, when the class is marked as private, it is hidden from all the classes in the codebase, you can think that the rest of the code won't even know that, that class exists.
Members of a private class are only accessible within the class and are hidden from the outside world.
A private member will remain inaccessible for the outside world even if its class is marked as public.
Now, for the second question: What is the functionality/use of these?
Access modifiers are especially useful when you want to restrict as to what part of your class should be accessible from outside and what part should not be accessible.
For example, in general, it is a good idea to make class variables as private and then expose functions that will allow you to fetch those variables, the major benefit you get with this approach is that at any point of time in future, you can change how those variables are calculated and the changes would propagate to all the classes without having the need to change them, had the classes directly accessed the variable, it would have been very difficult to make the change without impacting other classes. This is just one example demonstrating how useful access modifiers can prove to be even for the simplest of things.
Hope this gives you a brief idea.

I'm a self-taught programmer so did i understand these concepts? can someone include example too [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So someone tell me if i'm correct or not.
Encapsulation is Data hiding, allowing yourself only to view the
attributes and othering methods in a class privately, while you could you use these methods and abbritures in other classes,
Inheritance is extending a class, like taking some of the methods in the “super class” and pass it in “child class” and modify it or use it there.
Polymorphism is the same thing as inheritance but it's just formatted differently, like if i had an animal class, every animal has a different sound so, from there I would have something like this
Animal cat = new Cat();
overriding & overloading I’m not sure about this one
Abstract classes is taking methods or variables from the super class and pass those methods and variables as “Abstract” so that in the sub class you modify them and edit them.
Does that make sense? Or I misunderstood something?
These things all work together.
An object is something that is self-sufficient, it keeps track of its own state. Encapsulation enforces that separation, the object publishes methods that other objects call, but those methods are responsible for modifying the object's state.
In oo systems that use classes the class is a template for creating objects. Subclassing means creating a new class that is a more specific version of the subclassed class, where subclassed objects inherit the class definitions that specify the methods and fields of the superclasses.
Abstract classes defer some method implementations, leaving them to the subclasses to implement. If the superclass knows something has to happen at some particular point but wants to leave exactly what happens to the discretion of the specific objects, that's what abstract methods are for.
There's a pattern emerging here: objects taking responsibility for themselves, and a hierarchy of types from most abstract/general to most concrete/specific. Polymorphism is about objects' behavior being determined at the time the program runs based on what methods are overridden. Overriding means the subtype has a more specific version of a method that is substituted for the superclass version.
(Overloading otoh is a convenience for allowing a class to have methods with the same name but different parameters.)
The result of this can be a system that at a high level deals with abstract types and lets the objects themselves work out the exact details. The idea is that that way the details can be confined to the subclasses and the program can be modified by creating new subclasses without disrupting the rest of the program. In theory anyway, see Wadler's Expression Problem for where this all goes to hell.
And for examples: read the source that comes with the Jdk. The packages java.lang and java.util have a lot of classes that are examples of OO design.

Access modifiers in Java compared to c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've seen some discussions in StackOverflow about this subject, but I didn't see something that helped me understand the following point:
I'm coming from C++ background and lately I started to learn Java.
In C++ when protected is used only a subclass can access the member (the analog to Field in Java).
In C++ there is also the "friend" classes that can have access to private/protected mambers of the class that giving "friendship".
This is little bit analogous to "package" field modifier in Java (default field modifier), except that in C++ a friendship gives access to all private members, but in Java the access from classes in the same package is specific for a class field.
What I couldn't understand is, assuming that I want to give access only to subclasses, this is something I can do in C++ by declaring the members protected in a class that doesn't "give" friendships.
But in Java, I don't know how can I do it, since by using "protected" field modifier - I also give access to all classes in the package.
The only way that I find to do it is to declare the field protected and have the class isolated in its package.
From here, what I conclude is that the grouping of classes in one package must be done on basis of "friendship" between the classes.
Is this indeed the leading consideration in package grouping?
Another thing I don't understand,
In Java, assuming I have two fields in the class A: b,c.
I want to give B access to b but not to c,
and I want to give C access to c but not to b.
and to the "World" I want b,c to be hiden.
How can it be done?
I guess B,C should be both in the same package as A.
but by declaring b,c with package modifier I let B,C access both to b and c.
Is there a way in Java to do it?
Hope for some explanation of this subject
In C++ when protected is used only a subclass can access the member
(the analog to Field in Java).
Access specifiers are also for member functions / methods, not just member variables / fields.
In C++ there is also the "friend" classes that can have access to
private/protected mambers of the class that giving "friendship". This
is little bit analogous to "package" field modifier in Java (default
field modifier), except that in C++ a friendship gives access to all
private members, but in Java the access from classes in the same
package is specific for a class field.
There are not only friend classes but also functions.
It's true that Java's package-private access is similar, but it's not a complete replacement. A better way to put it would be that those two features have a subset of problems they solve. There are problems that can be solved by friend but not by package-private, and vice versa.
What I couldn't understand is, assuming that I want to give access
only to subclasses, this is something I can do in C++ by declaring the
members protected in a class that doesn't "give" friendships.
But in Java, I don't know how can I do it,
The answer is: You cannot.
since by using "protected" field modifier - I also give access to
all classes in the package.
Exactly.
The only way that I find to do it is to declare the field protected and
have the class isolated in its package.
Technically, yes. But this creates other problems. Your class will no longer be able to access package-private elements of its previous package. Let's say your BaseClass used to be in com.example.one. You move it to com.example.two. Now it will no longer be able to access other package-private classes of com.example.one.
Is this indeed the leading consideration in package grouping?
Yes, Java is designed like this. You can try to fight the language rules, but that's a losing battle in any programming language.
Another thing I don't understand, In Java, assuming I have two fields
in the class A: b,c. I want to give B access to b but not to c, and I
want to give C access to c but not to b. and to the "World" I want b,c
to be hiden. How can it be done?
It cannot be done in a clean way (by clean I mean: without any hacks that would require you to inspect the call stack at runtime and throw exceptions).
If you are concerned about this scenario because you are designing a public API, a low-tech solution which usually works perfectly is to create one or more *.internal packages and clearly document the fact that those are not supposed to be used in client code.
Those are quite a bunch of questions together...
But in Java, I don't know how can I do it, since by using "protected" field modifier - I also give access to all classes in the package.
True, there's no way to give access only to subclasses but not to classes in the same package. It was a design decision taken ages ago...
The only way that I find to do it is to declare the field protected and have the class isolated in its package.
This is technically correct, though it would be of little usage. Packaging of classes is meant to be used for grouping related classes, where 'related' means "classes that fulfil a specific relation", i.e. they belong to the same use case, belong to the same architectural layer, are in charged of the same entity, etc.
From here, what I conclude is that the grouping of classes in one package must be done on basis of "friendship" between the classes. Is this indeed the leading consideration in package grouping?
I believe I have already answered this in the preceding paragraph: packaging is meant to group related classes according to some specific criteria.
For your A, B and C classes example with attributes:
I guess B,C should be both in the same package as A. but by declaring b,c with package modifier I let B,C access both to b and c. Is there a way in Java to do it?
The answer is no, there's no simple, clean way to do it. You could achieve it with some hack or some more advanced techiques, but, again, this was part of the decisions taken by language designers ages ago...
It is implicitly assumed that all classes in a package "know" each other (because they were written by the same person/company/organization). So they either don't access protected fields, or, if they do, they know how to do it properly.
The assumption is that classes in the same package are more related to each other than a parent is to a derived class, because the derived class might virtually be written by anyone else. So they decided private protected is more restricted than protected.
So, I think you should not worry about the way classes in the same package can access each others' fields. In general, I just don't use this feature, except when I write iterators.
If you have two fields, you might make them internal classes, so that they have access to private fields (again, the logic is: if a class is inside another class, it knows about the semantic of that class) and can expose this access to their derived classes via protected methods.
Of course, you can invent some complex token exchange protocol to only make that field accessible to instances of B/C, but it'd be a remarkable overhead, and another object can still use reflection to gain access to all private members, unless you disable it via security policies, which isn't usually the case, but again, security policies are ultimately decided by the owner of the JVM.
So, in the end, the preferred way to do what you say in Java is to either put them in the same package or write B and C as internal classes of A, so that they can directly access private members of A and expose them to their derived classes.
public class A {
public static abstract class B {
protected Whatever getWhatever(A a) { return a.b; }
protected void setWhatever(A a, Whatever value) { a.b = value; }
}
public static abstract class C {
protected Whatever getWhatever(A a) { return a.c; }
protected void setWhatever(A a, Whatever value) { a.c = value; }
}
private Whatever b;
private Whatever c;
}
again, you always assume classes in the same package will never do anything bad.
Short answer: there's no way to do it.
If you're worried about intrusion from clients injecting a class in your package to gain illegal access, you can move the sensitive code in a separate package, and make the package sealed in the jar you deliver it in: http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html

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.

Working with a superclasses private member (Java)

I have build a subclass from a class in Java that has private methods which I want to access in the subclass, I cannot change or edit the superclass. The problem is of course they are private. Suppose I have written the superclass by myself and there were certain reasons why these methods have to be private. I could copy the code in the subclass. But is there a better way (without producing so much lines of code) to get able to work with them when writing a subclass?
Ignoring that your reasons for wanting to do this are potentially very bad (there's no contract for your usage of private variables, so there are no guarantees that they won't change, or disappear completely!) you could probably do what you want using reflection:
Using:
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredField(java.lang.String)
http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible(boolean)
http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#get(java.lang.Object)
Class c = object.getClass();
Field field = c.getDeclaredField("somePrivateInstanceVariable");
field.setAccessible(true);
Object someValue = field.get(object);
I just want to emphasise that you should consider the reasons for doing this and decide against it! If you own the code that you are extending, consider if you should instead make the field protected instead of private. Remember, hooking into code you're not supposed to have access to breaks OOP principles (you're circumventing encapsulation) and there are no guarantees the code your application depends on won't disappear in an update to the library (so you're also locking yourself down to a fixed version of the lib).
So you tried with "extends" to inherit the methods from the superclass. And of course they are private, but you can use them in the sublass. Making them abstract would force you to rewrite every in private, i see no other option.
Make super class method's protected. It would be only accessible from sub-class and package.
private modifier's are only accessible with in class.
In your case you should declare the private method as protected instead. Read this for more details on the subject.

Categories