Solved

static method overriding vs normal non static method overriding in child class

Posted on 2016-08-15
13
77 Views
Last Modified: 2016-08-26
Hi,

How static method overriding vs normal non static method overriding in child class are different?. child Static method overriding hides parent class static method right which is same with non static methods also right? When we use each one. Please advise

public class Parent {
    public static void test() {
        System.out.println("test from Parent class");
    }
}

public class Child extends Parent {
    public static void test() {
        System.out.println("test from Child");
    }
}


now non static case as below

public class Parent {
    public void test() {//non static
        System.out.println("test from Parent class of nonstatic");
    }
}

public class Child extends Parent {
    public  void test() {//non static
        System.out.println("test from Child of nonstatic");
    }
}
0
Comment
Question by:gudii9
  • 9
  • 3
13 Comments
 
LVL 10

Expert Comment

by:Jeffrey Dake
ID: 41757374
Static methods are mot really overridden but rather hidden. Since you make a call to static methods through the class, you can still call the static method in the base class by referencing it

Parent.test() vs  Child.test()

Both will work and call the static function declared in the classes.

However when you have a regular method. The method being called will be whichever the class implements.

Here is a good description. https://docs.oracle.com/javase/tutorial/java/IandI/override.html
0
 
LVL 7

Author Comment

by:gudii9
ID: 41758104
public 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) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}

The Cat class overrides the instance method in Animal and hides the static method in Animal. The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

The static method in Animal
The instance method in Cat


Cat myCat = new Cat();
        Animal myAnimal = myCat;

as above after creating cat object(myCat) why they are assigning to Animal instance ie myAnimal
0
 
LVL 7

Author Comment

by:gudii9
ID: 41758436
package com.upcast;

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) {
		Cat myCat = new Cat();
		Animal myAnimal = myCat;
		myAnimal.testClassMethod();
		myAnimal.testInstanceMethod();
	}
}

Open in new window


i changed
Animal.testClassMethod();
to
myAnimal.testClassMethod();

still got same output as
The static method in Animal
The instance method in Cat


what is exact meaning of hiding? i did not get that. i understood oerriding part of parent method with child method which dominates
0
 
LVL 5

Accepted Solution

by:
Jan Louwerens earned 250 total points
ID: 41758702
The non-static cases is the concept of Polymorphism. The actual method called is based on the actual type of the object on which the method is called.

Static methods do not have an associated object. The correct version needs to be explicitly called:
Animal.testClassMethod();
// vs
Cat.testClassMethod();

Open in new window


This type of code is confusing, and should generate a warning in the compiler:
Animal myAnimal = myCat;
myAnimal.testClassMethod();   // this line should generate a compiler warning, since a static method is being called on an object, rather than explicitly stating which version is intended

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 41758747

This type of code is confusing, and should generate a warning in the compiler:

i see warning but it does work though giving below output

The static method in Animal
0
 
LVL 7

Author Comment

by:gudii9
ID: 41758748
what is it exactly hiding here? why it is called hiding?

Cat myCat = new Cat();        

 Animal myAnimal = myCat;

as above after creating cat object(myCat) why they are assigning to Animal instance ie myAnimal??
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 7

Author Comment

by:gudii9
ID: 41763766
when i try this example getting error
http://crunchify.com/java-method-hiding-and-overriding-override-static-method-in-java/

package com.solution;

import com.upcast.Company;

/**
 * @author Crunchify.com
 */
 
public class CrunchifyHideStaticMethod {
	public static void main(String args[]) {
		Company cmp = new CrunchifyCompany();
		// if we can override static, this should call method from Child class
		cmp.staticMethod(); // Eclipse should show warning: The static method
							// staticMethod() from the type Company should be
							// accessed in a static way
		cmp.nonStaticMethod();
	}
}
 

Open in new window


package com.solution;
// CrunchifyCompany: Sub-Child Class
class CrunchifyCompany extends Company {
	/*
	 * static method of same name and method signature as existed in super
	 * class, this is not method overriding instead this is called method hiding
	 * in Java
	 */
	public static void staticMethod() {
		System.err.println("CrunchifyCompany: Overridden Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("CrunchifyCompany: non-Static method");
	}
}

Open in new window


package com.solution;
// Comapny: Super-Parent Class
class Company {
 
	// public static method which can not be overridden in Java
	public static void staticMethod() {
		System.out.println("Company: Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("Company: non-Static method");
	}
}
 

Open in new window


package com.solution;

public class CohesionExampleProblemSolution {
}

class InternetDownloader {
	void downloadFromInternet() {

	}

	class DataParser {
		void parseData(String content) {

		}
	}

	class DatabaseStorer {

		void storeIntoDatabase(String data) {

		}
	}

	void doEverything() {
		new InternetDownloader().downloadFromInternet();
		new DataParser().parseData();
		new DatabaseStorer().storeIntoDatabase();

	}
}
/*
 * public class CohesionExampleProblem{
 * 
 * }
 */

Open in new window


my error is'

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
      Type mismatch: cannot convert from CrunchifyCompany to Company
      The method staticMethod() is undefined for the type Company
      The method nonStaticMethod() is undefined for the type Company

      at com.solution.CrunchifyHideStaticMethod.main(CrunchifyHideStaticMethod.java:11)



please advise
0
 
LVL 10

Assisted Solution

by:Jeffrey Dake
Jeffrey Dake earned 250 total points
ID: 41764071
Looks like you are importing a different Company class. Your example creates a class Company in the com.solution package, however in your CrunchifyHideStaticMethod class you are importing com.upcast.Company. This is a different class with the same name which is why you get the error.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41764414
it got resolved.

I wonder why we got below output

Company: Static Instance method
CrunchifyCompany: non-Static method


i expected as below?

CrunchifyCompany: Overridden Static Instance method
CrunchifyCompany: non-Static method

please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 41764434
package com.solution;

import com.solution.Company;

/**
 * @author Crunchify.com
 */
 
public class CrunchifyHideStaticMethod {
	public static void main(String args[]) {
		Company cmp = new CrunchifyCompany();
		// if we can override static, this should call method from Child class
		cmp.staticMethod(); // Eclipse should show warning: The static method
							// staticMethod() from the type Company should be
							// accessed in a static way
		cmp.nonStaticMethod();
	}
}
 

Open in new window


package com.solution;
// CrunchifyCompany: Sub-Child Class
class CrunchifyCompany extends Company {
	/*
	 * static method of same name and method signature as existed in super
	 * class, this is not method overriding instead this is called method hiding
	 * in Java
	 */
	public static void staticMethod() {
		System.err.println("CrunchifyCompany: Overridden Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("CrunchifyCompany: non-Static method");
	}
}

Open in new window


package com.solution;
// Comapny: Super-Parent Class
class Company {
 
	// public static method which can not be overridden in Java
	public static void staticMethod() {
		System.out.println("Company: Static Instance method");
	}
 
	// non static method
	public void nonStaticMethod() {
		System.out.println("Company: non-Static method");
		System.out.println("test commit in git");
	}
}
 

Open in new window


package com.solution;

public class CohesionExampleProblemSolution {
}

class InternetDownloader {
	void downloadFromInternet() {

	}

	class DataParser {
		void parseData(String content) {

		}
	}

	class DatabaseStorer {

		void storeIntoDatabase(String data) {

		}
	}

	void doEverything() {
		new InternetDownloader().downloadFromInternet();
		new DataParser().parseData();
		new DatabaseStorer().storeIntoDatabase();

	}
}
/*
 * public class CohesionExampleProblem{
 * 
 * }
 */

Open in new window

0
 
LVL 10

Expert Comment

by:Jeffrey Dake
ID: 41764768
This is why it is not recommended to call a static method via an object. Since that reference was typed as a Company it calls that method. Most editors, like eclipse will give you a warning. You really should call static methods directly like Company.staticMethod();
0
 
LVL 7

Author Comment

by:gudii9
ID: 41767217
cmp.staticMethod(); // Eclipse should show warning: The static method
                                          // staticMethod() from the type Company should be
                                          // accessed in a static way
            cmp.nonStaticMethod();


so i modified as below to make compiler happy


company.staticMethod(); // Eclipse should show warning: The static method
                                          // staticMethod() from the type Company should be
                                          // accessed in a static way
            cmp.nonStaticMethod();


to conclude:

so method call is happened generally based on the reference type right  but in case of non static overridden method it happens instead of reference type based on actual object type right?

but in case of  static overridden method it happens instead of reference type best to use class name  and call is based on actual classobject type right even though method seems like overrident but it is not but just hiding there ?
0
 
LVL 7

Author Comment

by:gudii9
ID: 41767231
https://docs.oracle.com/javase/tutorial/java/IandI/override.html

in above link

The second class, a subclass of Animal, is called Cat:

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) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;//what is the need of this step. why assigning mycat to myAnimal. it makes no sense to me????
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}
The Cat class overrides the instance method in Animal and hides the static method in Animal. The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

The static method in Animal
The instance method in Cat
As promised, the version of the hidden
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now