Java inherited method using the wrong class - java

So I have a parent class, here refered to as A, and class B which extends A.
public class A
{
private int a = 1;
public int getA()
{
return a;
}
}
public class B extends A
{
private int a = 2;
}
However, when B.getA() is called, it returns 1 from class A instead of the 2 in class B. Did I do something wrong? Because I had a similar problem a couple of months ago, and it miraculously worked after a lot of messing around. The only difference is that the method deals with adding an object to an ArrayList.
Thanks.

Private variables are private even to subclasses. A.a and B.a are two completely different fields. If you want to change data in a subclass, make it a protected field or (better yet) add an optionally abstract getter to the parent class and override it in the subclass.

The reason is that the fields defined in a class are never overriden in subclasses, irrespective of the fields' access modifiers.
If you declare a field in a subclass with the same name as a field in the superclass, your subclass actually has two fields with that name. The field inheritted from the superclass is hidden in the subclass, but (if the access rules permit it) the superclass version can be accessed in the subclass; e.g. by qualifying the field name with the class name.
(In your particular example, the access rules forbid B to access the a declared in A. A private field or method can only be accessed from the class itself or nested classes. But even so, there are two fields called a in any B instance instance.)

Related

Create an instance of subclass inside superclass

Whenever I create an instance of superclass, I want it to automatically create one instance of the subclass. Then I can access the subclass from an instance of the superclass.
Here I have a superclass name "SortArticles":
public class SortArticles {
private String title;
private String linkToFullArticles;
private FullArticle fullArticleObject;
public String getTitle() {
return this.title;
}
public FullArticle getFullArticleObject() {
return this.fullArticleObject;
}
}
Here I have a subclass name "FullArticle":
public class FullArticle extends SortArticles {
private List<Label> labelList;
}
I want to call like this:
ArrayList<SortArticles> sortList = new ArrayList<>();
sortList.add(new SortArticles());
sortList.get(0).getFullArticleObject().getTitle;
Is it possible to do that? I think of using HashMap to link sort and full, but I need create 2 arraylist, and link it manually.
You are misunderstanding the concept of inheritance.
You can say, that dog is an animal, but you can't know, that the animal, generally, barks, for sure.
It's children, who get properties of parents, not vice versa. When you instantiate some SuperClass, it's not instantiated along with its subclass(es) members, and it should never be.
For example, if you instantiate java.lang.Object, it should never (and it will never) have any members of your (let's say) Employee class; however, your Employee will always inherit all the non-private members of all its parents.
Besides, imagine you have hundred classes extending one SuperClass. Would you expect (or would you want, after all) the instance of your SuperClass, to contain all the non-private members of all hundred classes deriving from it? shall instance of java.lang.Object contain all the non-private infrastructure available on the class-path?
No, that's bad, that's wrong, that's not logical.

(Field hiding) When does it make sense to use both a subclass field and its hidden superclass field?

In Java (as with most OO languages), you can have two classes, with one extending the other. You can have instance fields with the same name in both classes, where the subclass' instance field hides the superclass' instance field. An example is written below.
class A{
int i;
}
class B extends A{
int i;
}
This means that when the object is created, it has both its B instance field, i, and its A instance field, i. One might think that you would never want this, and that when you conceptually create a new "i" in class B, it means "the one and only i that is relevant to this object". When is this not the case? Give an example of two classes where we want to keep both instance variables and modify them.

Java subclass calling superclass

I'm having a little trouble with inheritance. What i have done is made a superclass as some of the attributes in the subclasses were identical.
I am trying to reference the superclass, I tried putting super(name); above the line name = replacementName; it will not compile saying name has private access in the Superclass 'person'. I know that it won't access a private field but how can I get the name from the superclass in a subclass method?
Here is the method.
public void changeName(String replacementName){
name = replacementName;
}
Help appreciated.
You have several options :
1 - In your super class, use private declaration for the name attribute and add public (or protected) getters/setters. Then you can modify your super class field from your child class using the setter method.
2 - In your super class, use protected declaration for your name field. Then you can access it directly from your child class.
...

why subclass over riding can only have weaker access than super class

When it comes to over - riding , there is only one rule related to access specifiers
"The subclass overridden method cannot have weaker access than super class method"
why is the child class restricted to have stronger access specifier ?
what draw back may it invite , I am guessing something to occur on design level.
let us consider the rule didn't exist , in that case
1 : parent class having weaker access say public
2 : child class having stronger access say private
so if any external class tries to access the method , it still can access from child class as it will be inherited in child class and will be available to use with object reference
please clarify.
public class A
{
public void methOne(int a)
{
// something
}
}
class B extends A
{
private void methOne(int a)
{
// something else
}
}
class C
{
public static void main(String args[])
{
new B().methOne();
// in this special case after removing the specifier rule it will execute the method from parent class.
}
}
What you have tried to do is invalid, because by extending A all instances of B must be able to act as though they were an A. For example:
A a = new A();
a.methOne(1);
Compared to:
A a = new B();
a.methOne(1);
In both cases all the code knows is that it has an A and that all As have a method called methOne. In the second case that is broken as you have tried to make the method private but A has already said that it has a method by that name available.
It works the other way around because you don't invalidate the contract. If the method was private in A and public in B then you can still use an instance of B as though it was an A, you just don't have access to that method unless you know you are working with a B.
When you re declare the method of your parent class in you child class it is method overriding which in simple terms would mean you would want the objects of your child class to call its method instead of the parents method with same name and signature. Now in child class if you have a more restrictive access specifier say by making private as in your case you are effectively telling the JVM not to call the method though it is visible to the child objects which would lead to confusion as if you have exposed only your parent class to outside world then in some of your classes if you could make this method private then JVM shouldnot allow these methods to be called if such child objects are passed .
Q. so if any external class tries to access the method , it still can access from child class as it will be inherited in child class and will be available to use with object reference
This in your above case defeats the purpose of encapsulation by making the method private. By declaring a method private you are actually trying to tell that make my parent class corresponding method not visible to outside world which is not posssible as your parent method is visible to your child class.

Why have public methods inside private classes?

I was going through a part of a code which was something like this
// compare points according to their polar radius
public static final Comparator<Point2D> R_ORDER = new ROrder();
.
.
.
private static class ROrder implements Comparator<Point2D> {
public int compare(Point2D p, Point2D q) {
double delta = (p.x*p.x + p.y*p.y) - (q.x*q.x + q.y*q.y);
if (delta < 0) return -1;
if (delta > 0) return +1;
return 0;
}
}
Why do we have such public methods inside private static classes. What harm would it do if i made ROrder
Non-Static
Public
ROrder Non-Static
By making it non-static you will need the instance of the container class to create the instance of ROder, which maybe due to the design of the class would not make logic. You should keep class non-static only when you really need the instance of outer class to get the instance of inner class.
ROrder Public
Again because they wanted to restrict the use of ROrder outside the context of this class. They did not want any client code or other code to freely create instances of ROrder, as they would not be of any use.
Why do we have such public methods inside private static classes.
In this case because you are implementing an interface Comparator and you will pass this comparator for other uses, such as sorting and you would want the Collections class to have the visibility of compare method, so the method has to be public even if the class implementing the interface is private.
So this is just a logical way to enhance the readability and intent of use of the code.
Logical Use
This class wants the string to be in some format.
public class SomeClass{
private static class StringHelper{
//will do the task of parsing and validating that string object
}
}
Now in this case you would not want to keep StringHelper class public, as its use is too localized to be reused. So you would rather emphasize that by keeping it private. And there can be methods that are public if StringHelper implemented some interface.
UPDATE:
You should keep class non-static only when you really need the
instance of outer class to get the instance of inner class.
On that I think the answer can be too broad, but I would try to explain in short. By that what I mean was that if the inner class object shares some state of the outer object on which its processing is dependent, then you will need the object of outer class to share its state with the inner class object, but if the inner class instance is independent of the state of outer class, then it is safe to keep the inner class static.
This class implements Comparator and so must implement its methods. The implementation methods can't be static. Also, since interface methods are implicitly public, they must be declared public, regardless of the containing class's visibility. Try not doing so and it will fail to compile. This is certainly the reason it is declared public here -- it can't not be.
This is true regardless of whether the containing class is static or public. Here, it could be either of those things and the method inside would still have to be public and non-static.
Other methods that don't implement an interface could be private, and, logically probably should inside a private class as there would be no point in declaring it otherwise -- but it would be allowed by Java syntax.
All private members (fields, classes, whatever) are only visible inside the class. So, it doesn't matter what visibility you give a method of a private class - all methods will only be visible inside the containing class, because the class itself is private.
If the inner class implements an interface or extends a class, overridden methods may not have less visibility than the declaration in the super type, so that's one reason to have public methods in a private inner class.
However, although the syntax allows private classes to have public methods, it won't increase the visibility of those methods sufficiently to be visible outside the containing class. There are several examples in java of modifiers being legal but having no effect, such as inner interfaces being implicitly static (whether or not the static keyword is used).
This class is private because developer did not want to ROrder be instantiated in other place. But an instance can be accessed through the constant R_ORDER from other classes.
The method is public for two reason : first, compare is defined in the Comparator interface. Second, as R_ORDER is accessible from other classes, it is more than convenient to be able to call a method on this object. In this case, it is compare.
Finally, if the class was not static, it would keep a reference to the parent class, which is almost always not needed

Categories