Understanding the use of Super to access Superclass members - java

I was referring to the java language specification to understand the use of super. While I understand the first use case i.e.
The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.
I can't seem to understand the following use case:
The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.
Could someone please explain this with the help of code?
I suppose the following could be illustrative of the second case:
class S{
int x=0;
}
class T extends S{
int x=1;
class C{
int x=2;
void print(){
System.out.println(this.x);
System.out.println(T.this.x);
System.out.println(T.super.x);
}
}
public static void main(String args[]){
T t=new T();
C c=t.new C();
c.print();
}
}
output:
2
1
0

I believe it applies to this situation
public class Main {
static class Child extends Parent{
class DeeplyNested {
public void method() {
Child.super.overriden();
}
}
public void overriden() {
System.out.println("child");
}
}
static class Parent {
public void overriden() {
System.out.println("parent");
}
}
public static void main(String args[]) {
Child child = new Child();
DeeplyNested deep = child.new DeeplyNested();
deep.method();
}
}
In the JLS
The form T.super.Identifier refers to the field named Identifier of
the lexically enclosing instance corresponding to T, but with that
instance viewed as an instance of the superclass of T.
Identifier is overriden, the method.
Here, the lexically enclosing instance is of type Child and its superclass is Parent. So T.super refers to the instance of Child viewed as Parent.
The code above prints
parent

Related

Methods with the same name and variables with same name in parent-child relation

class Super {
public Integer i = 1;
void Sample() {
System.out.println("method of super class");
}
}
public class Sub extends Super {
public Integer i = 1000;
void Sample() {
System.out.println("method of sub class");
}
public static void main(String args[]) {
Super obj;
obj = new Super();
obj.Sample();
System.out.println(obj.i);
obj = new Sub();
obj.Sample();
System.out.println(obj.i);
}
}
Output:
method of superclass
1
method of subclass
1
When the Sample() method is called we get consequently different outputs (method of super class/subclass)
But when the variable, i is printed, outputs are identical (1)
Are problems the reference/object types or inheritance rules?
Variables in Java do not follow polymorphism and overriding is only applicable to methods, not variables. Thus, you see the overriding behaviour for the method, Sample() but not for the variable, i.
Note that in this case, the child class variable hides the parent class variable and the concept is known as variable hiding.
Note: Always follow the Java naming conventions e.g. you should rename the method, Sample() to sample().

Error -- Super class constructor in Eclipse with Java 8

I am coding in eclipse and new to java, inherited method and calling parent method with super() keyword showing error in Java-8 also the new Child(); method is also showing error. File name is Example.java
public class Example{
class Parent{
void parentMethod(){
System.out.println("Parent Method");
}
void parentMethod(int a){
System.out.println("Parent Method: One Argument");
}
void parentMethod(int a, int b){
System.out.println("Parent Method: Two Argument");
}
}
class Child extends Parent{
void childMethod() {
super(10);
System.out.println("Child Method");
}
}
public static void main(String[] args) {
new Child();
System.out.println("Main Class Method: no argument");
}
}
it gives an error in eclipse :
in line 15: Multiple markers at this line
- Line breakpoint:Public$Child [line: 15] -
childMethod()
in line 20: No enclosing instance of type Public is accessible. Must qualify the allocation with an enclosing
instance of type Public (e.g. x.new A() where x is an instance of Public).
.
;
.
super(10); can only be used inside a constructor (not inside a method) to call the constructor of the super class (the class being extended), e.g. if you have Parent(int a) { ... }, you can do Child() { super(10); }; or if you want to call the existing method of the super class (instead of the non-existing super constructor with a single number parameter) use super.parentMethod(10); instead
new Child(); does not work inside a static method for a non-static nested class; a non-static inner class belongs to an instance of the outer class: new Example().new Child(); would work here instead; alternatively, since in the example the nested classes do not make use of instance methods and fields of Example, you can make the classes Parent and Child static to fix the error: static class Parent{ and static class Child extends Parent{

This keyword referring to a parent variable

Today a fellow learner came up with an interesting query. We know that this keyword is used to refer to the current object. But I could not explain to him how this keyword behaves as seen in the following snippet. I know what inheritance is: allows access to parent class variables and methods. But are they copied into the memory area of child instance?, because I am able to use this keyword to access the parent class property.
I was able to refer to parent class variable. I searched and found that nothing gets copied virtually to child class, but why the following behavior happens? Please explain this case of using this.
class Parent {
int a=10;
}
public class Child extends Parent{
void m1(){
System.out.println(a);
System.out.println(this.a);
System.out.println(super.a);
}
public static void main(String[] args){
new Child().m1();
}
}
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The property a is inherited by Child. Therefore, you can use this.a in child to reference it.
Where was the problem supposed to be?
I searched and found that nothing gets copied virtually to child class
You have the wrong example to illustrate that statement.
The way to understand that is (roughly): "instance variables are not overridden when re-declared in subclasses, so you can't declare an instance as Parent and expect to get Child.a if the instance was created with new Child()". Here's an example of the problematic case:
class Parent {
int a = 10;
}
public class Child extends Parent{
int a = 12; //not overridden
public static void main(String[] args){
Parent child = new Child();
System.out.println(child.a); //This will print 10, not 12
}
}
System.out.println(child.a); will print 10 because variables instance fields don't get overridden. You get the value based on the declared type (Parent in this case)
When you instantiate a class Child it contains all members of itself and of Parent. However, private members of Parent are not accessible from Child:
class Parent {
private int p = 10;
}
public class Child extends Parent{
void m1(){
System.out.println(p); // compilation error
}
}
Another interesting case is when one instance of Parent tries to access a private field of another instance of Parent. What do you think happens?
public class Parent {
private int p = 11;
public boolean same(Parent other) {
return other.p == p;
}
}
You might think other.p will result in a compilation error since p is a private field. However, since privacy does not pertain to object instances, but to classes. So all private fields in Parent are visible within all Parent instances, so this works!
Consider below Code:
this is a reference variable which will point to the current object.
super is used to refer to Parent's property in case you have created
the same in the child.
class Product{
String color;
public Product() {
color = "Black";
}
}
class Mobile extends Product{
String color;
Mobile(){
color = "White";
}
void showMobileData(){
System.out.println("this hashCode is "+this.hashCode());
System.out.println("super hashCode is: "+super.hashCode());
System.out.println("color is: "+color);
System.out.println("this.color is: "+this.color);
System.out.println("super.color is: "+super.color);
}
}
public class Test {
public static void main(String[] args) {
//new Mobile().showMobileData();
Mobile mRef = new Mobile();
System.out.println("mRef HashCode: "+mRef.hashCode());
mRef.showMobileData();
}
}

Variables binding VS method binding in polymorphism

I observer the behaviour that when we call a variable from a polymorphic object then it calls the parent's variable but when we call a method with the same polymorphic object then it calls child's method.Why this is the behaviour of polymorphism in Java? Why doesn't Java handle polymorphic variables and methods in same way?
class Parent{
int age =10;
public void showAge(){
System.out.println("Parent Age:"+age);
}
}
class ChildOne extends Parent{
int age = 20;
public void showAge(){
System.out.println("child one age:"+age);
}
}
class ChildTwo extends Parent{
int age = 30;
public void showAge(){
System.out.println("Child Two Age:"+age);
}
}
public class Test{
public static void main(String[] args) {
Parent parentChildOne = new ChildOne();
System.out.println("parentChildOne.age: "+parentChildOne.age);
parentChildOne.showAge();
Parent parentChildTwo = new ChildTwo();
System.out.println("parentChildTwo.age: "+parentChildTwo.age);
parentChildTwo.showAge();
}
}
Here is the output:
parentChildOne.age: 10
child one age:20
parentChildTwo.age: 10
Child Two Age:30
First of all keep in mind that Your variables are not polymorphic and the next climax thing is your this point
Parent parentChildOne = new ChildOne();
Parent parentChildTwo = new ChildTwo();
See when you are trying to call a method using Parent parentChildOne then it should call the child's method because it is overrided and according to polymorphism it should be called. Now see again Parent parentChildOne same object for variables , now here is nothing with polymorphism but jvm is dealing it now with the concept of shadowingSo thats why they both are showing their real behavioursPlease follow this tutorial of shadowing in java
Variables are not polymorphic in Java.
Instead, instance variables in child classes shadow instance variables with the same name in the parent class.
See also Can parent and child class in Java have same instance variable?
parentChildOne and parentChildTwo are of type Parent. So you are printing age of the Parent. Same happes with the showAge() method but the value of age is shadowed by the child classes.
Please see the comments into,
class Parent{
int age =10;
public void showAge(){
System.out.println("Parent Age:"+age);
}
}
class ChildOne extends Parent{
//when you extends Parent the inherited members are like
//and initialized into the default constructor
// int super.age =10;
int age = 20;
public void showAge(){
System.out.println("child one age:"+age);
}
}
class ChildTwo extends Parent{
//when you extends Parent the inherited members are like
//and initialized into the default constructor
// int super.age =10;
int age = 30;
public void showAge(){
System.out.println("Child Two Age:"+age);
}
}
public class Test{
public static void main(String[] args) {
Parent parentChildOne = new ChildOne();
// when we call like this, goes to the parent type of the variable instead of object.
System.out.println("parentChildOne.age: "+parentChildOne.age);
parentChildOne.showAge();
Parent parentChildTwo = new ChildTwo();
// when we call like this, goes to the parent type of the variable instead of object.
System.out.println("parentChildTwo.age: "+parentChildTwo.age);
parentChildTwo.showAge();
}
}

How to make some methods from superclass not avaliable in child class

Lets say I have a class
public class Base {}
and a child class
public class Derived extends Base {
public void Foo(Object i){
System.out.println("derived - object");
}
}
and main class
public class Main {
public static void main(String[] args) {
Derived d = new Derived();
int i = 5;
d.Foo(i);
}
}
In console we will see
derived - object
Some time later I want to modify my superclass like this :
public class Base {
public void Foo(int i) {
System.out.println("base - int");
}
}
Now if I run my programm I will see:
base - int
So can I make a method in superclass not avaliable in my child class?
In result I want to see derived - object.
I see some don't understand what I want so I'll try to explain:
I want to modify only superclass and I don't want to modify my child class.. for example if I will make jar with my superclass and jar with my childs. I don't want to change all jars.. I want to add method into superclass and make it avaliable for superclass..
And such code
public class Main {
public static void main(String[] args) {
Derived d = new Derived();
int i = 5;
d.Foo(i);
Base b = new Base();
b.Foo(i);
}
}
give me
derived - object
base - int
You should use following signature for Foo method in base class:
public void Foo(Object i) {
System.out.println("base - int");
}
This way you can override method Foo from base class. Now you do not override this method but overload it instead.
If you want to use public void Foo(int i) signature in your base class then you can define Foo method in base class as private.
PS: I hope that I've understood you.
private members are limited to the class scope.
default (no keyword for this one) are limited to other members of the same package.
protected are limited to hierarchy.
public are not limited.
So if you don't want your child class to access a member of the superclass (member means methods, enum, variables ...) you should declare your foo like this :
public class Base {
private void Foo(int i) {
System.out.println("base - int");
}
}
Edit from my comment :
if you dont want child class to access a parent's member at compile time I can't see any way to still allow external classes to access it.
You want to block access from close scope while allowing broader scope. This can only be done by overriding the method and throwing an exception for accessviolation or something which is not at compile time but at runtime. Although you could make it work with a custom annotations but I don't know how to do this.
You can make a method final, which means, that the child class cannot override it.
If you do not do that and the child class overrides the method, you cannot call the super classes method from your main.
A Convention note: Please use lowercase method names in java.
package com.abc;
public class TestParentChild {
public static void main(String[] asd) {
Base b = new ChildB();
b.foo(5);
}
}
class Base {
public void foo(int i) {
System.out.println("derived - int");
}
}
class ChildB extends Base {
public void foo(int i) {
System.out.println("derived - object");
}
}
This might help you

Categories