Static / Compile-time Polymorphism [duplicate] - java

This question already has answers here:
What is the difference between dynamic and static polymorphism in Java?
(14 answers)
Closed 3 years ago.
Why method overloading called as static or compile-time polymorphism
sample in Java.
class StaticPolymorphismSample {
void polymorphicMethod(int a) {
}
void polymorphicMethod(int a, int b) {
}
void polymorphicMethod(String a) {
}
void nonPolymorphicMethod(int a) {
}
void nonPolymorphicMethod1(int a) {
}
}
so my question is.
Why we say that method overloading ( in this case polymorphicMethod methods ) are static polymorphism , but another methods( nonPolymorphicMethod(int a) nonPolymorphicMethod1(int a) ) are not polymorphism.
technically I cannot see different between method with same name and different parameters and method with different,
all answers in here and topics in google is not applicable for my question.

For nonPolymorphicMethod1(int a) the reason this wouldn't be considered polymorphic is because it has a different name from the other nonPolymorphicMethods.
For nonPolymorphicMethod( int a, int b ) and nonPolymorphicMethod( int a ) these aren't considered polymorphic as they don't take the same parameters. Edit This is Wrong See Next Line
The other methods you've shown are polymorphic due to their sharing of a name, but differing parameter types or number of parameters.
A better example of polymorphism in methods would be :
public abstract class ClassA
{
public Object getObject()
{
return new Object();
}
}
public class ClassB extends ClassA
{
#Override
public ClassB getObject()
{
return new ClassB();
}
}
public class ClassC extends ClassA
{
#Override
public ClassC getObject()
{
ClassC example = new ClassC();
example.doStuff();
return example;
}
private void doStuff()
{
// Do Something To Change The Object
}
}

Related

tricky method Overloading in java [duplicate]

This question already has an answer here:
Method overloading/overriding in Java subclass object with superclass reference variable
(1 answer)
Closed 6 years ago.
class ABC {
void doMe(String s) {
System.out.println("String");
}
}
class XYZ extends ABC {
void doMe(Object o) {
System.out.println("Object");
}
}
public class StopStart {
public static void main(String[] args){
ABC o = new XYZ();
o.doMe(null);
}
}
What will happen and why?
string class extends Object. So which doMe() will execute.
Is it a compilation error?
Overloading is resolved in compile time, according to the compile time type of the variable o. Therefore doesn't matter which methods are defined in the XYZ sub-class. Only the methods of ABC are relevant.
Therefore only void doMe(String s) is considered by the compiler, and that's the chosen method.

Class variable not instantiated in subclass Java [duplicate]

This question already has answers here:
What's wrong with overridable method calls in constructors?
(8 answers)
Closed 6 years ago.
I have the following code: The constructor of class A calls an abstract method implemented by class B which returns a variable from class B. This variable will be null by the time A calls the abstract method even if I instantiated it in the declaration. Is there any way I can instantiate it this way?
public abstract class A {
public A() {
isStringNull();
}
protected abstract String getMyString();
private void isStringNull () {
if (getMyString() == null) {
System.out.println("String is null :(");
} else {
System.out.println(getMyString());
}
}
}
public class B extends A {
private String amINull = "Of course not";
#Override
protected String getMyString() {
return amINull;
}
}
public static void main(String[] args) {
new B();
}
Can somebody please explain why the string will be null?
There is a detailed explanation of the order of initialization here:
Java order of Initialization and Instantiation
Basically, if you call a superclass constructor (explicitly or implicitly by inheritance and having an argumentless constructor), all of its initialization is done before it comes back to the subclass. So, in this case, the order is:
perform class A variable initializers
perform class A constructor body
return to class B constructor
perform class B variable initializers
perform class B constructor body
This is happening because you are first checking is string null and then you are assigning its value. When you extend some class, that class code will be executed at first!
Your compiler is doing it this way:
new B() -> isStringNull() -> private String amINull = "Of course not";
Check this modified code and see what will happen and look at execution steps
public abstract class A {
public A() {
System.out.println("Class A() called");
isStringNull();
}
protected abstract String getMyString();
private void isStringNull () {
if (getMyString() == null) {
System.out.println("String is null :(");
} else {
System.out.println(getMyString());
}
}
}
public class B extends A {
System.out.println("Class B() called");
private String amINull = "Of course not";
#Override
protected String getMyString() {
return amINull;
}
}
public static void main(String[] args) {
new B();
}

How interface support multiple inheritance [duplicate]

This question already has answers here:
Multiple inheritance on Java interfaces
(5 answers)
Closed 7 years ago.
public class Test implements X, Y { //X.Y interface are shown below
public void myMethod() {
System.out.println(" Multiple inheritance example using interfaces");
}
public static void main(String[]args) {
Test t=new Test();
t.myMethod();
System.out.println(t.a); //compile time error ambigious field
}
}
Please help me to solve this issue
interface X {
public void myMethod();
int a = 0;
}
interface Y {
int a = 9;
public void myMethod();
}
Any variable defined in an interface is, by definition, public static final, in other words it's just a constant, it's not really a field (since there are no fields in interfaces).
So the compilation error you get points out that the compiler doesn't know witch constant you refer to.
You have 2 options here:
change the name of the constant in one of the interfaces, for example in interface Y declare int b = 9;
inside the main method point to a concrete constant: System.out.println(X.a);
Adding to one of the answer already provided.
If a class implements two interfaces and each interface have method with same signature and same name, then you are effectively defining only one method and they are same. If you have two methods of same name but different return types then there will be a compilation error.
Example ->
public interface A {
int a = 0;
void myMethod();
}
public interface B {
int a = 0;
void myMethod();
}
public class Test implements A, B {
#Override
public void myMethod() {
// My method is defined for both A and B
System.out.println(" Multiple inheritance example using interfaces");
}
public static void main(String[] args) {
Test object = new Test();
((A)(object)).myMethod();
((B)(object)).myMethod();
System.out.println(((A)object).a); //To print constant of A
System.out.println(((B)object).a); //To print constant of B
}
}
//Let's see other example
public interface A {
void myMethod();
}
public interface B {
boolean myMethod(); //changed void to boolean
}
public class Test implements A, B {
#Override
public void myMethod() { //Compilation error here, return type is incompatible
}
}
myMethod implements both myMethod declarations. I believe your problem is that in the two separate interfaces a has different values and is before and after the declaration of myMethod. The order is not important, since myMethod will surely be called after the declaration of a, but the difference of a values might cause some logical discrepancies. Maybe you could implement a getter for it as well, to handle the situation.

How to use values of local variables in inherited functions of java? [duplicate]

This question already has answers here:
Java Inheritance - instance variables overriding
(3 answers)
Closed 7 years ago.
I have 2 classes A and B such that
public class A {
public String a = "hey";
public void printA() {
System.out.println(a);
}
and
public class B extends A{
public String a = "Jude";
}
What do I need to do so that the output of the lines below is Jude
B object = new B();
object.printA(); //This should output Jude
You cannot access the subclass field from the superclass. However you can change it in subclass like this:
public class B extends A {
B() {
this.a = "Jude";
}
}
This way you don't declare the new field, but change the value of existing one. Note that extends A is necessary to specify that B is subclass of A.
Alternatively you may consider using a method instead of field:
public class A {
public String getA() {
return "hey";
}
public void printA() {
System.out.println(getA());
}
}
public class B extends A {
#Override
public String getA() {
return "Jude";
}
}
Note that in Java "variable" term usually applied to local variables declared within methods. You are speaking about "field", not "variable".
Fields can not be overridden. Methods can; use methods instead:
public class A {
public String getA() {
return "hey";
}
public void printA() {
System.out.println(getA());
}
}
public class B extends A {
public String getA() {
return "Jude";
}
}
That's all. If getA() is not called outside these classes, cincdider making it protected.
Just change your declaration of a to this.a like so.
public class B extends A{
B(){
super();
//Could hardcode this.a to "Jude" here if you want.
}
B(String word){
super();
this.a = word;
}
}
a is already defined for B from the superclass A so you need to use "this" to access it.
You can use it like so
B object = new B("Jude");
object.printA(); //"Jude"
The Java® Language Specification, Java SE 8 Edition
If the class declares a field with a certain name, then the
declaration of that field is said to hide any and all accessible
declarations of fields with the same name in superclasses, and
superinterfaces of the class.
Not sure If I need to further explain it for the audience, but YOU CANNOT "use values of local variables in inherited functions of java", why? See above.

Create instance of a generic class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create instance of generic type in Java?
I got these classes
public abstract class Base {
public String Id = "originalId";
}
public class InstanceOfBase extends Base {
public void setString(String test) {
this.Id = test;
}
}
public class UseIt {
public Test<InstanceOfBase> test = new Test<InstanceOfBase>();
public void run() {
InstanceOfBase instanceOfBase = test.createMe();
System.out.println(instanceOfBase.Id);
}
}
public abstract class Test<E extends Base> {
public E createMe() {
// How do I do this?
return new E();
}
}
The code above does not compile because it does not know how to create E. how can I achieve this?
When I invoke the run method, I expect it should print "originalId".
Unfortunately you cannot create classes from generic types in java. But you can do as Justin Rudd suggested in this thread and write:
public E createMe(Class<E> clazz)
{
return clazz.newInstance();
}
So you use the class archetype to create a new instance. Invoking it could be:
InstanceOfBase instanceOfBase = test.createMe(test.getClass)

Categories