Is this the case of method hiding? - java

i have following code in which the base class Employee have a static method meth1() which i am able to call from a child class (Pro) object . Is it a case of method hiding or what ? , i am not sure because i haven't implemented the meth1() method in Pro class, but still able to call Emplyee static method from Pro object.
class Employee
{
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
protected static void meth1()
{
System.out.println("inside emp-meth1");
}
}
public class Pro extends Employee {
/*
* public void meth1()
{
System.out.println("inside encapsulation-meth1");
}
*/
public static void main(String as[])
{
Pro e = new Pro();
// e.s ="jay";
e.meth1();
}
}
Output:
inside emp-meth1
Thanks
Jayendra

What are you trying to hide?
Try the below code
emp.meth1() will call method based on reference not based on the object being referred.
class Employee
{
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
protected static void meth1()
{
System.out.println("inside emp-meth1");
}
}
public class Pro extends Employee {
protected static void meth1()
{
System.out.println("inside encapsulation-meth1");
}
public static void main(String as[])
{
Pro e = new Pro();
Employee emp = new Pro();
emp.meth1(); //this is case of method hiding
e.meth1();
}
}

Related

Why the Instance<Object> is null?

I have the following structure:
public class StringFactory {
#Inject
private Instance<StringFormatter> formatterInstances;
#PostConstruct
public void init() {
for (AddressFormatter formatter : formatterInstances) {
System.out.println("String formater: " + formatter);
}
}
}
StringFormatter
interface StringFormatter {
String createFormattedString(final String x);
}
StringFormaterForKR
public class StringFormaterForKR implements StringFormatter {
#Override
public String createFormattedString(String x) {
return null;
}
DefaultStringFormater
public class DefaultStringFormater implements StringFormatter {
#Override
public String createFormattedString(String x) {
return null;
}
Test
public class Test() {
public static void main(String args[]) {
StringFactory factory = new StringFactory();
}
}
I don't understand why formatterInstances is null ?
And I saw that the message from PostConstruct is never printed...
Do you have any explication for this ?

Reason for ambiguous error in java generics code while trying to overload/override

While going through generics, I am not able to understand why the error is coming:
class Box <T> {
private T theThing;
public Box( T t) { theThing = t; }
public void reset( T t) { theThing = t; }
}
class WordBox< S extends CharSequence > extends Box< String > {
public WordBox( S t) { super(t.toString().toLowerCase()); }
public void reset( S t) {
// super.reset(t.toString().toLowerCase());
}
}
public class ss {
public static void main(String[] args) {
WordBox<String> city = new WordBox<String>("Skogland");
city.reset("Stavanger"); // error: ambiguous**
}
}
I can understand, method worldbox.reset () is not overriding the method from BOX, instead it is overloading.
After type erasure, I am assuming this will be code :
class Box {
private Object theThing;
public Box( Object t) { theThing = t; }
public void reset( Object t) { theThing = t; }
}
class WordBox extends Box{
public WordBox( CharSequence t) { super(t.toString().toLowerCase()); }
public void reset( CharSequence t) {
super.reset(t.toString().toLowerCase());
}
}
public class ss {
public static void main(String[] args) {
WordBox<String> city = new WordBox<String>("Skogland");
city.reset("Stavanger");
}
}
So, city.reset("Stavanger") should call the method from Worldbox.reset , as String extends charsequence and it seems to be closest match.
Could anyone please explain why the ambiguous error is coming in this code?

how to "pull down" a parameter when refactor in eclipse?

before refactor:
public interface Service {
public void hello(Person p);
}
public class BlackPersonServiceImpl implements Service {
#Override
public void hello(Person p) {
//...
}
}
public class WhitePersonServiceImpl implements Service {
#Override
public void hello(Person p) {
//...
}
}
public class BeforeRefactor {
public static void main(String[] args) {
String str = args[0];
Person p = JSON.parseObject(str, Person.class);
Service service = getServiceFromSpringContainer();
service.hello(p);
}
private static Service getServiceFromSpringContainer() {
//...
return null;
}
}
after refactor:
public interface Service {
public void hello(String str);
}
public class WhitePersonServiceImpl implements Service {
#Override
public void hello(String str) {
Person person = JSON.parseObject(str, Person.class);
//do something to person...
//...
}
}
public class AfterRefactor {
public static void main(String[] args) {
String str = args[0];
Service service = getServiceFromSpringContainer();
service.hello(str);
}
private static Service getServiceFromSpringContainer() {
//...
return null;
}
}
That's what I want(I think "pull down" is not the "right" word to describe it...).
I tried "introduce parameter object" in eclipse, and it does not work.
There are many implementations of "Service". I dont want to change them one by one.
Is there a good way to solve this problem?
Thanks!
You can do it somewhat for a single class and a single method (although it's akward and a succession of small refactoring steps), but not across several types at the same time.

#MockClass is not working

I am new to jmockit and trying to execute the following online example.
The #MockClass is not working. My BookStore's getBookTitle() method is calling the function of orginal class instead of the mock class.
BookStore class:
public class BookStore {
public String getBookTitle(String isbn){
return BookStoreService.getBookTitle(isbn);
}
}
BookStoreService class:
public class BookStoreService {
public static String getBookTitle(String isbn){
return "Random";
}
}
Test class:
public class BookStoreTest {
private static Map<String, String> bookMap = new HashMap<String, String>(2);
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
}
#MockClass(realClass = BookStoreService.class)
public static class MockBookstoreService {
#Mock
public static String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
}
#Test
public void testGetBookTitle() throws Exception {
System.out.println("in testGetBookTitle()");
final String isbn = "0553293354";
final String expectedTitle = "Foundation";
BookStore store = new BookStore();
String title = store.getBookTitle(isbn);
System.out.println(title); // This prints "Random" instead of "Foundation"
Assert.assertEquals(title, expectedTitle);
}
}
PS: I am using TestNG
Using the latest stable version of jmockit you could do it like this:
#BeforeClass
public static void setup() {
System.out.println("in setup()");
bookMap.put("0553293354", "Foundation");
bookMap.put("0836220625", "The Far Side Gallery");
new MockUp<BookStoreService>() {
#Mock
public String getBookTitle(String isbn) {
System.out.println("in getBookTitle()");
if (bookMap.containsKey(isbn)) {
return bookMap.get(isbn);
} else {
return null;
}
}
};
}
Remove the obsolete block:
public static class MockBookstoreService{...}

Storing Methods in an Enum? [duplicate]

This question already has an answer here:
Methods in Enums [duplicate]
(1 answer)
Closed 8 years ago.
Right now, I have an enum for a variety of values, and I was wondering if there is any way I would be able to store a method in an enum. For example:
public enum myEnum{
one("first", callFirstMethod),
two("second", callSecondMethod),
three("last", callThirdMethod);
public String message;
public Method met;
myEnum(String m, Method meth){
message = m;
met = meth;
}
}
public class myMethods{
public void callFirstMethod(){
System.out.println("First!");
}
public void callSecondMethod(){
System.out.println("Second!");
}
public void callThirdMethod(){
System.out.println("Third!");
}
}
Then by using something like:
Method method = myEnum.one.callFirstMethod();
To call the method. Is something like this possible? I've tried playing around/looking around on google, and nothing is really turning up. Thank you for the help!
Use an interface and have the interface instance as the second enum parameter, or give it an abstract method that is implemented in the instance. For instance:
enum MyEnum {
ONE("first", new MyInterface() {
#Override
public void commonMethod() {
System.out.println("First!");
}
}) {
#Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, first!");
}
},
TWO("second", new MyInterface() {
#Override
public void commonMethod() {
System.out.println("Second!");
}
}) {
#Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, second!");
}
},
THREE("last", new MyInterface() {
#Override
public void commonMethod() {
System.out.println("Third!");
}
}) {
#Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, third!");
}
};
private String message;
private MyInterface myType;
private MyEnum(String m, MyInterface myType) {
message = m;
this.myType = myType;
}
public String getMessage() {
return message;
}
public MyInterface getMyType() {
return myType;
}
public void enumMethod() {
System.out.println(message);
}
public abstract void abstractEnumMethod();
}
interface MyInterface {
void commonMethod();
}
The answer all depends on what it's you want to achieve. For example, you could provide a common method within you enum and inspect the instance of the enum calling it...
public class TestEnum {
public static void main(String[] args) {
MyEnum.ONE.doStuff();
MyEnum.TWO.doStuff();
MyEnum.THREE.doStuff();
}
public enum MyEnum {
ONE("first"),
TWO("second"),
THREE("last");
public String message;
MyEnum(String m) {
message = m;
}
public void doStuff() {
System.out.println(name());
if (ONE.equals(this)) {
System.out.println("...Do stuff for one");
} else if (TWO.equals(this)) {
System.out.println("...Do stuff for two");
} else if (THREE.equals(this)) {
System.out.println("...Do stuff for three");
}
}
}
}
Which outputs...
one
...Do stuff for one
two
...Do stuff for two
three
...Do stuff for three

Categories