OOP inheritance execution - java

Why does the execution of TestClass.main() outputs 202 202 101??
class BaseClass
{
int data = 101;
public void print()
{
System.out.print(data + " ");
}
public void fun()
{
print();
}
}
class SubClass extends BaseClass
{
int data = 202;
public void print()
{
System.out.print(data + " ");
}
}
class TestClass
{
public static void main(String[] args)
{
BaseClass obj = new SubClass();
obj.print();
obj.fun();
System.out.print(obj.data);
}
}
With my poor OOP knowledge I think the execution must be this way:
1- obj.print(); prints 202 from SubClass
2- Since there is no obj.fun(); method in Subclass it calls parent method so the output should be 101
3- System.out.print(obj.data); should print 202 since the value is overridden in subclass.
So I think the output would be 202 101 202 but it isn't, can you explain me why?

Since there is no obj.fun(); method in Subclass it calls parent method so the output should be 101
Indeed, it calls the super class for fun, but the super class calls print, and as print is overridden, the overriding version (in the subclass) gets called.
System.out.print(obj.data); should print 202 since the value is overwritten in subclass.
Variables are not overriden, but hidden by subclass, as obj declared as BaseClass, it accesses it data property directly. unlike method call, this is decided at compile time.

Because method are polymorphic and fields are not
if you remove
int data = 101;
from your BaseClass it will not compile

The trick is in deciding which method is executed. That choice is made from the type of the instance of the object. In your case, obj is a SubClass and every call to print() will execute the print method of SubClass. This mechanism is called Polymorphism in OOP.
Instead of mixing methods and variables, I'd recommend you start by just doing some testing on methods only. The code is mostly the same, with the same Polymorphism behavior, but without the variables.
class BaseClass
{
public void print()
{
System.out.print(101 + " ");
}
public void fun()
{
print();
}
}
class SubClass extends BaseClass
{
public void print()
{
System.out.print(202 + " ");
}
}
class TestClass
{
public static void main(String[] args)
{
BaseClass obj = new SubClass();
obj.print();
obj.fun();
}
}

1 and 2 - methods are polymorphic - method from base class will use method from sub class, if it will be able and ofc if you have reference to sub class
3 - field isnt polymorphic. It's taken from the type of reference.

Related

What does Java `this` actually refer to in an inheritance situation?

Why does the following Java code produces:
10
superclass
The code in question is:
class SuperClass {
int a;
public SuperClass() {
this.a = 10;
}
private void another_print() {
System.out.println("superclass");
}
public void print() {
System.out.println(this.a);
this.another_print();
}
}
class SubClass extends SuperClass {
int a;
public SubClass() {
this.a = 20;
}
private void another_print() {
System.out.println("subclass");
}
public void print() {
super.print();
}
}
public class Main {
public static void main (String[] args) {
SubClass c = new SubClass();
c.print();
}
}
There is no instance of SuperClass ever created, isn't there?
Not only that Java starts looking for the method to invoke from the SuperClass, it even somehow knows that a = 10!
Let's consider a similar Python code:
class SuperClass:
def __init__(self):
self.a = 10
def another_prn(self):
print('superclass')
def prn(self):
print(self.a)
self.another_prn()
class SubClass(SuperClass):
def __init__(self):
self.a = 20
def another_prn(self):
print('subclass')
def prn(self):
super().prn()
c = SubClass()
c.prn()
It works as I expect:
20
subclass
The only explanation that my colleagues (Python disliking Java folks) came up with is: "Python is not a true OOP language". Not very convincing at all.
Update: private void another_print() is my blunder, I should have used protected.
It is the order of constructor calling in Java.
In the SubClass, when you instantiate c, the constructor implicitly calls the default constructor of the SuperClass (public SuperClass()) (it must do so). Then a is set to be 10 in the SuperClass.
Now that we're done with the SuperClass constructor, we get back to the constructor of SubClass, which assigns a = 20. But fields are not subject to overriding in java, so a in SuperClass is still 10.
After that it's pretty obvious, we call c.print() which calls the print of SubClass, which calls the print of SuperClass (by super.print()), which prints a which is as you remember 10. Then another_print (which is not overridden since it is private) just prints superclass and we're done.
In the sub-class's print you just call super-class's print method.
So it prints the a from the super class of course.
You have two separate a fields here. Fields are not subject to overriding, only methods are. The super-class has an a field and you have another a field in the sub-class.
If another language produces another result, that's not a big surprise. Also, I am not sure your Python code is logically equivalent/analogous to your Java code.
My comment explained the reason your code probably doesn't work as expected.
Below is code written how you most likely expected it to work. Note the comments in the code.
static class SuperClass {
int a; // only declare field in superclass to avoid hiding
public SuperClass() {
this.a = 10;
}
// make method protected, public, or package private to allow children to override it
protected void another_print() {
System.out.println("superclass");
}
public void print() {
System.out.println(this.a);
this.another_print();
}
}
static class SubClass extends SuperClass {
public SubClass() {
this.a = 20;
}
#Override
protected void another_print() {
System.out.println("subclass");
}
public void print() {
super.print();
}
}
public static void main (String[] args) {
SubClass c = new SubClass();
c.print();
}
This will print
20
subclass
I've debugged my slightly corrected code and found out that:
this is an instance of SubClass
Unlike Python, Java is ok with more than one variable of the same name (as peter.petrov mentioned in his answer, but I didn't got it right away)
One of the as is from the SubClass and the second is from the SuperClass (as implicit superclass constructor call, again unlike Python)
this.a has a different value in test_super() and test_sub() and that is the magic, given that this is a SubClass and Java documentation reads:
this is a reference to the current object — the object whose method or constructor is being called
I think I can live with the fact that this will have all the variables from the whole dependency tree and Java will select which one to use depending on the context.

Java constructor order of calling [duplicate]

I ended up the following scenario in code earlier today (which I admit is kinda weird and I have since refactored). When I ran my unit test I found that a field initialization was not set by the time that the superclass constructor has run. I realized that I do not fully understand the order of constructor / field initialization, so I am posting in the hopes that someone explain to me the order in which these occur.
class Foo extends FooBase {
String foo = "foobar";
#Override
public void setup() {
if (foo == null) {
throw new RuntimeException("foo is null");
}
super.setup();
}
}
class FooBase {
public FooBase() {
setup();
}
public void setup() {
}
}
#Test
public void testFoo() {
new Foo();
}
The abbreviated backtrace from JUnit is as follows, I guess I expected $Foo.<init> to set foo.
$Foo.setup
$FooBase.<init>
$Foo.<init>
.testFoo
Yes, in Java (unlike C#, for example) field initializers are called after the superclass constructor. Which means that any overridden method calls from the constructor will be called before the field initializers are executed.
The ordering is:
Initialize superclass (recursively invoke these steps)
Execute field initializers
Execute constructor body (after any constructor chaining, which has already taken place in step 1)
Basically, it's a bad idea to call non-final methods in constructors. If you're going to do so, document it very clearly so that anyone overriding the method knows that the method will be called before the field initializers (or constructor body) are executed.
See JLS section 12.5 for more details.
A constructor's first operation is always the invocation of the superclass constructor. Having no constructor explicitely defined in a class is equivalent to having
public Foo() {
super();
}
The constructor of the base class is thus called before any field of the subclass has been initialized. And your base class does something which should be avoided: call an overridable method.
Since this method is overridden in the subclass, it's invoked on an object that is not fully constructed yet, and thus sees the subclass field as null.
Here's an example of polymorphism in pseudo-C#/Java:
class Animal
{
abstract string MakeNoise ();
}
class Cat : Animal {
string MakeNoise () {
return "Meow";
}
}
class Dog : Animal {
string MakeNoise () {
return "Bark";
}
}
Main () {
Animal animal = Zoo.GetAnimal ();
Console.WriteLine (animal.MakeNoise ());
}
The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.
class A
{
A(int number)
{
System.out.println("A's" + " "+ number);
}
}
class B
{
A aObject = new A(1);
B(int number)
{
System.out.println("B's" + " "+ number);
}
A aObject2 = new A(2);
}
public class myFirstProject {
public static void main(String[] args) {
B bObj = new B(5);
}
}
out:
A's 1
A's 2
B's 5
My rules:
1. Don't initialize with the default values in declaration (null, false, 0, 0.0...).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice. (the most important rule)
public class Dice
{
private int topFace = 1;
private Random myRand = new Random();
public void Roll()
{
// ......
}
}
or
public class Dice
{
private int topFace;
private Random myRand;
public Dice()
{
topFace = 1;
myRand = new Random();
}
public void Roll()
{
// .....
}
}

Can a private method in super class be overridden in the sub-class?

Can private methods be overridden in Java?
If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
No, you are not overriding it. You can check by trying to mark it with #Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base {
private void func(){
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func();
}
}
class Derived extends Base {
public void func(){ // Is this an overriding method?
System.out.println("In Derived Class func method");
}
}
class InheritDemo {
public static void main(String [] args) {
Derived D = new Derived();
D.func2();
}
}
It will print:
func2
In base func method
When you change func() in Base to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.
No, it is not. You can mark an override just to make sure like this:
#Override
public void func(){
System.out.println("In Derived Class func method");
}
And in this case it would be a compiler error.
You are not overriding. You cannot override private members, you are merely defining a new method in Derived. Derived has no knowledge Base's implementation of func() since its declared as private. You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func(). To be clear: it would be incorrect to say you are overriding Base's implementation of func().
In addition to the already correct answer, consider this:
public class Private {
static class A {
public void doStuff() {
System.out.println(getStuff());
}
private String getStuff() {
return "A";
}
}
static class B extends A {
public String getStuff() {
return "B";
}
}
public static void main(String[] args) {
A a = new A();
a.doStuff();
a = new B();
a.doStuff();
B b = new B();
b.doStuff();
}
}
This will print
A
A
A
although B "overrides" getStuff(). As implementation of doStuff() is fixed to calling A#getStuff(), no polymorphism will be triggered.
Nope because if you do something like Base b = new Derived(); you still won't be able to call b.func(). What you're doing is called "hiding".
Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method.
So this is not the case of overriding
Method hiding will be happening here instead of overriding. like what happens in case of static.
Actually,you are not overriding.Before Java5
an overridden method's return type must match with parent class's method.
But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
you can follow this thread :Can overridden methods differ in return type?
The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. The function in the derive class is an independent function that can be access by anywhere.
The code would run the function in the derived class
A private method can never be over ridden. It is always hidden.
In your example - Derived class has one parent class private method and has its own function func. Both are different, and the func is not over ridden. Its a separate independent function.
If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding
Note : An object defines the members which it has, and a reference defines which it can access
// Method Over ridding case
class Base{
public void func(){
System.out.println("Parent class");
};
public void func1(){
func();
}
}
class Derived extends Base{
public void func(){
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1(); // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class
}
}
// Method Hidding case - Private and static methods case
class Base{
private void func(){
System.out.println("Parent class");
};
public void func1(){
func()
}
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1();
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.
b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function.
}
}
Read comments in the below code snippet to find the answer.
Sources:
Definition reference:
Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'.
public class Deer {
public Deer() { System.out.print("Deer"); }
public Deer(int age) { System.out.print("DeerAge"); }
private boolean hasHorns() { return false; }
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println(","+deer.hasHorns());// false is printed.
}
}
class Reindeer extends Deer {
public Reindeer(int age) { System.out.print("Reindeer"); }
private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context.
// Below code is added by me for illustration purpose
public static void main(String[] args) {
Deer deer = new Reindeer(5);
//Below line gives compilation error.
//System.out.println(","+deer.hasHorns());
}
}

Overriding vs Hiding Java - Confused

I'm confused on how overriding differs from hiding in Java. Can anyone provide more details on how these differ? I read the Java Tutorial but the sample code still left me confused.
To be more clear, I understand overriding well. My issue is that I don't see how hiding is any different, except for the fact that one is at the instance level while the other is at the class level.
Looking at the Java tutorial code:
public class Animal {
public static void testClassMethod() {
System.out.println("Class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("Instance " + " method in Animal.");
}
}
Then we have a subclass Cat:
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
Then they say:
The output from this program is as follows:
Class method in Animal.
The instance method in Cat.
To me, the fact that calling a class method testClassMethod() directly from the Animal class executes the method in Animal class is pretty obvious, nothing special there. Then they call the testInstanceMethod() from a reference to myCat, so again pretty obvious that the method executed then is the one in the instance of Cat.
From what I see, the call hiding behaves just like overriding, so why make that distinction? If I run this code using the classes above:
Cat.testClassMethod();
I'll get:
The class method in Cat.
But if I remove the testClassMethod() from Cat, then I'll get:
The class method in Animal.
Which shows me that writing a static method, with the same signature as in the parent, in a subclass pretty much does an override.
Hopefully I'm making clear my where I'm confused and someone can shed some light. Thanks very much in advance!
Overriding basically supports late binding. Therefore, it's decided at run time which method will be called. It is for non-static methods.
Hiding is for all other members (static methods, instance members, static members). It is based on the early binding. More clearly, the method or member to be called or used is decided during compile time.
In your example, the first call, Animal.testClassMethod() is a call to a static method, hence it is pretty sure which method is going to be called.
In the second call, myAnimal.testInstanceMethod(), you call a non-static method. This is what you call run-time polymorphism. It is not decided until run time which method is to be called.
For further clarification, read Overriding Vs Hiding.
Static methods are hidden, non-static methods are overriden.
The difference is notable when calls are not qualified "something()" vs "this.something()".
I can't really seem to put it down on words, so here goes an example:
public class Animal {
public static void something() {
System.out.println("animal.something");
}
public void eat() {
System.out.println("animal.eat");
}
public Animal() {
// This will always call Animal.something(), since it can't be overriden, because it is static.
something();
// This will call the eat() defined in overriding classes.
eat();
}
}
public class Dog extends Animal {
public static void something() {
// This method merely hides Animal.something(), making it uncallable, but does not override it, or alter calls to it in any way.
System.out.println("dog.something");
}
public void eat() {
// This method overrides eat(), and will affect calls to eat()
System.out.println("dog.eat");
}
public Dog() {
super();
}
public static void main(String[] args) {
new Dog();
}
}
OUTPUT:
animal.something
dog.eat
This is the difference between overrides and hiding,
If both method in parent class and child class are an instance method, it called overrides.
If both method in parent class and child class are static method, it called hiding.
One method cant be static in parent and as an instance in the child. and visa versa.
If I understand your question properly then the answer is "you already are overriding".
"Which shows me that writing a static method, with the same name as in the parent, in a subclass pretty much does an override."
If you write a method in a subclass with exactly the same name as a method in a superclass it will override the superclass's method. The #Override annotation is not required to override a method. It does however make your code more readable and forces the compiler to check that you are actually overriding a method (and didn't misspell the subclass method for example).
Overriding happens only with instance methods.
When the type of the reference variable is Animal and the object is Cat then the instance method is called from Cat (this is overriding). For the same acat object the class method of Animal is used.
public static void main(String[] args) {
Animal acat = new Cat();
acat.testInstanceMethod();
acat.testClassMethod();
}
Output is:
The instance method in Cat.
Class method in Animal.
public class First {
public void Overriding(int i) { /* will be overridden in class Second */ }
public static void Hiding(int i) { /* will be hidden in class Second
because it's static */ }
}
public class Second extends First {
public void Overriding(int i) { /* overridden here */ }
public static void Hiding(int i) { /* hides method in class First
because it's static */ }
}
The rule for memorizing is simple: a method in an extending class
can't change static to void and
can't change void to static.
It will cause of compile-error.
But if void Name is changed to void Name it's Overriding.
And if static Name is changed to static Name it's Hiding. (Both the static method of the subclass as well as the one of the superclass can be called, depending on the type of the reference used to call the method.)
In this code snippet I use 'private' access modifier instead of 'static' to show you difference between hiding methods and overriding methods.
class Animal {
// Use 'static' or 'private' access modifiers to see how method hiding work.
private void testInstancePrivateMethod(String source) {
System.out.println("\tAnimal: instance Private method calling from "+source);
}
public void testInstanceMethodUsingPrivateMethodInside() {
System.out.println("\tAnimal: instance Public method with using of Private method.");
testInstancePrivateMethod( Animal.class.getSimpleName() );
}
// Use default, 'protected' or 'public' access modifiers to see how method overriding work.
protected void testInstanceProtectedMethod(String source) {
System.out.println("\tAnimal: instance Protected method calling from "+source);
}
public void testInstanceMethodUsingProtectedMethodInside() {
System.out.println("\tAnimal: instance Public method with using of Protected method.");
testInstanceProtectedMethod( Animal.class.getSimpleName() );
}
}
public class Cat extends Animal {
private void testInstancePrivateMethod(String source) {
System.out.println("Cat: instance Private method calling from " + source );
}
public void testInstanceMethodUsingPrivateMethodInside() {
System.out.println("Cat: instance Public method with using of Private method.");
testInstancePrivateMethod( Cat.class.getSimpleName());
System.out.println("Cat: and calling parent after:");
super.testInstanceMethodUsingPrivateMethodInside();
}
protected void testInstanceProtectedMethod(String source) {
System.out.println("Cat: instance Protected method calling from "+ source );
}
public void testInstanceMethodUsingProtectedMethodInside() {
System.out.println("Cat: instance Public method with using of Protected method.");
testInstanceProtectedMethod(Cat.class.getSimpleName());
System.out.println("Cat: and calling parent after:");
super.testInstanceMethodUsingProtectedMethodInside();
}
public static void main(String[] args) {
Cat myCat = new Cat();
System.out.println("----- Method hiding -------");
myCat.testInstanceMethodUsingPrivateMethodInside();
System.out.println("\n----- Method overriding -------");
myCat.testInstanceMethodUsingProtectedMethodInside();
}
}
Output:
----- Method hiding -------
Cat: instance Public method with using of Private method.
Cat: instance Private method calling from Cat
Cat: and calling parent after:
Animal: instance Public method with using of Private method.
Animal: instance Private method calling from Animal
----- Method overriding -------
Cat: instance Public method with using of Protected method.
Cat: instance Protected method calling from Cat
Cat: and calling parent after:
Animal: instance Public method with using of Protected method.
Cat: instance Protected method calling from Animal
I think this is not yet fully explained.
Please see the following example.
class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}
public static void main(String[] args) {
Animal myCat = new Cat();
Cat myCat2 = new Cat();
myCat.testClassMethod();
myCat2.testClassMethod();
myCat.testInstanceMethod();
myCat2.testInstanceMethod();
}
}
The output will be as follows.
The static method in Animal
The static method in Cat
The instance method in Cat
The instance method in Cat
Based on my recent Java studies
method overriding, when the subclass have the same method with the same signature in the subclass.
Method hiding, when the subclass have the same method name, but different parameter. In this case, you're not overriding the parent method, but hiding it.
Example from OCP Java 7 book, page 70-71:
public class Point {
private int xPos, yPos;
public Point(int x, int y) {
xPos = x;
yPos = y;
}
public boolean equals(Point other){
.... sexy code here ......
}
public static void main(String []args) {
Point p1 = new Point(10, 20);
Point p2 = new Point(50, 100);
Point p3 = new Point(10, 20);
System.out.println("p1 equals p2 is " + p1.equals(p2));
System.out.println("p1 equals p3 is " + p1.equals(p3));
//point's class equals method get invoked
}
}
but if we write the following main:
public static void main(String []args) {
Object p1 = new Point(10, 20);
Object p2 = new Point(50, 100);
Object p3 = new Point(10, 20);
System.out.println("p1 equals p2 is " + p1.equals(p2));
System.out.println("p1 equals p3 is " + p1.equals(p3));
//Object's class equals method get invoked
}
In the second main, we using the Object class as static type, so when we calling the equal method in Point object, it's waiting a Point class to arrive as a parameter,but Object coming. So the Object class equals method getting run, because we have an equals(Object o) there. In this case, the Point's class equals dosen't overrides, but hides the Object class equals method.
public class Parent {
public static void show(){
System.out.println("Parent");
}
}
public class Child extends Parent{
public static void show(){
System.out.println("Child");
}
}
public class Main {
public static void main(String[] args) {
Parent parent=new Child();
parent.show(); // it will call parent show method
}
}
// We can call static method by reference ( as shown above) or by using class name (Parent.show())
The linked java tutorial page explains the concept of overriding and hiding
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Coming back to your example:
Animal myAnimal = myCat;
/* invokes static method on Animal, expected. */
Animal.testClassMethod();
/* invokes child class instance method (non-static - it's overriding) */
myAnimal.testInstanceMethod();
Above statement does not show hiding yet.
Now change the code as below to get different output:
Animal myAnimal = myCat;
/* Even though myAnimal is Cat, Animal class method is invoked instead of Cat method*/
myAnimal.testClassMethod();
/* invokes child class instance method (non-static - it's overriding) */
myAnimal.testInstanceMethod();
In addition to the examples listed above, here is a small sample code to clarify the distinction between hiding and overriding:
public class Parent {
// to be hidden (static)
public static String toBeHidden() {
return "Parent";
}
// to be overridden (non-static)
public String toBeOverridden() {
return "Parent";
}
public void printParent() {
System.out.println("to be hidden: " + toBeHidden());
System.out.println("to be overridden: " + toBeOverridden());
}
}
public class Child extends Parent {
public static String toBeHidden() {
return "Child";
}
public String toBeOverridden() {
return "Child";
}
public void printChild() {
System.out.println("to be hidden: " + toBeHidden());
System.out.println("to be overridden: " + toBeOverridden());
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.printParent();
child.printChild();
}
}
The call of child.printParent() outputs:
to be hidden: Parent
to be overridden: Child
The call of child.printChild() outputs:
to be hidden: Child
to be overridden: Child
As wee can see from the outputs above (especially the bold marked outputs), method hiding behaves differently from overriding.
Java allows both hiding and overriding only for methods. The same rule does not apply to variables. Overriding variables is not permitted, so variables can only be hidden (no difference between static or non-static variable). The example below shows how the method getName() is overriden and the variable name is hidden:
public class Main {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name); // prints Parent (since hiding)
System.out.println(p.getName()); // prints Child (since overriding)
}
}
class Parent {
String name = "Parent";
String getName() {
return name;
}
}
class Child extends Parent {
String name = "Child";
String getName() {
return name;
}
}
At runtime the child version of an overridden method is always executed for an instance
regardless of whether the method call is defi ned in a parent or child class method. In this
manner, the parent method is never used unless an explicit call to the parent method is
referenced, using the syntax
ParentClassName.method().
Alternatively, at runtime the parent
version of a hidden method is always executed if the call to the method is defined in the
parent class.
In method overriding, method resolution is done by the JVM on the basis of runtime object. Whereas in method hiding, method resolution is done by the compiler on the basis of reference.
Thus,
If the code would have been written as,
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.testClassMethod();
}
The Output would be as below:
Class method in Animal.
It is called hiding because the compiler hides the super class method implementation, when subclass has the same static method.
Compiler has no restricted visibility for overridden methods and it’s only during runtime that it’s decided which one is used.
This is the difference between overriding and hiding:
Animal a = new Cat();
a.testClassMethod() will call the method in parent class since it is an example of method hiding. The method to be called is determined by the type of the reference variable and decided at compile time.
a.testInstanceMethod() will call the method in child class since it is an example of method overriding. The method to be called is determined by the object which is used to call the method at runtime.
How is static method hiding happening in java?
Cat class is extending Animal class. So in Cat class will have both static methods (i mean Child class's static method and Parent class's static method)
But how JVM hiding Parent static method? How it's dealing in Heap and Stack?

super() in Java

Is super() used to call the parent constructor?
Please explain super().
super() calls the parent constructor with no arguments.
It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).
Also it can be used to call methods from the parent. I.e. super.aMethod()
More info and tutorial here
Some facts:
super() is used to call the immediate parent.
super() can be used with instance members, i.e., instance variables and instance methods.
super() can be used within a constructor to call the constructor of the parent class.
OK, now let’s practically implement these points of super().
Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.
Program 1
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
Output:
200
200
Now check out program 2 and try to figure out the main difference.
Program 2
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
Output:
100
200
In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.
OK, now check out the difference between program 3 and program 4.
Program 3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
Output:
200
Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.
Program 4
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
Output:
100
200
Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super()
Yes. super(...) will invoke the constructor of the super-class.
Illustration:
Stand alone example:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)
There is also a super keyword, that you can use in methods to invoke a method of the superclass
A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.
public class Alien{
public Alien(){ //Default constructor is written out by user
/** Implementation not shown…**/
}
}
public class WeirdAlien extends Alien{
public WeirdAlien(){
super(); //calls the default constructor in Alien.
}
}
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
I would like to share with codes whatever I understood.
The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-
1. Use of super with variables:
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:-
Maximum Speed: 120
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output:-
This is student class
This is person class
3. Use of super with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:-
Person class Constructor
Student class Constructor
What can we use SUPER for?
Accessing Superclass Members
If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName();
Invoking Superclass Constructors
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Look at the code below:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class
of the top layer in the inheritance tree.And then all the way down the inheritance tree.The
reason why this is possible to happen is that the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.If there's no non-argument constructor
in the superclass and the subclass doesn't explicitly say which of the constructor is to
be executed in the superclass,you'll get a compile-time error.
In the above code,if we want to create a Wolf object successfully,the constructor of the
class has to be executed.And during that process,the two-argu-constructor in the Animal
class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same
class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature
class and the non-argu-constructor again implicitly invokes the empty constructor in the Object
class.
Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :
public MyClass(int a) {
this(a, 5); // Here, I call another one of this class's constructors.
}
public MyClass(int a, int b) {
super(a, b); // Then, I call one of the superclass's constructors.
}
super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.
Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :
public String toString() {
int hp = this.hitpoints(); // Calls the hitpoints method in this class
// for this object.
String name = super.name(); // Calls the name method in the superclass
// for this object.
return "[" + name + ": " + hp + " HP]";
}
super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.
This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .
If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.
Here is an example of this:
class A {
A() {
System.out.println("Constructor A");
}
}
class B extends A{
public B() {
System.out.println("Constructor B");
}
}
class C extends B{
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
The above would output:
Constructor A
Constructor B
Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Usage of Java super Keyword
super can be used to refer to the immediate parent class instance variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor.
There are a couple of other uses.
Referencing a default method of an inherited interface:
import java.util.Collection;
import java.util.stream.Stream;
public interface SkipFirstCollection<E> extends Collection<E> {
#Override
default Stream<E> stream() {
return Collection.super.stream().skip(1);
}
}
There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass:
public class OuterInstance {
public static class ClassA {
final String name;
public ClassA(String name) {
this.name = name;
}
public class ClassB {
public String getAName() {
return ClassA.this.name;
}
}
}
public static class ClassC extends ClassA.ClassB {
public ClassC(ClassA a) {
a.super();
}
}
public static void main(String[] args) {
final ClassA a = new ClassA("jeff");
final ClassC c = new ClassC(a);
System.out.println(c.getAName());
}
}
Then:
$ javac OuterInstance.java && java OuterInstance
jeff

Categories

Resources