Trying to understand the basics of polymorphism in Java. - java

Can somebody please tell me if the keyword 'extends' must be an used (in the syntax) of child classes that overide methods of their super class.

The word extends is used to indicate for the whole class that this class is a sub-class of another class. It is not related to whether the sub-class overrides certain methods or not, that is entirely up to the sub-class class. The sub-class may decide to override none, some, or all of the methods of the super-class. The sub-class may override only methods which are not marked as final in the super-class.
Here is a somewhat trivial example:
class A {
// This is the super-class.
public void myMethod() {...};
}
class B extends A {
// This extends above says: B is sub-class of A.
// So this class B is the sub-class of A.
// You can override methods of A here, like this
public void myMethod() {...};
// but you're not required to override them.
}

Polymorphism in java is a concept by which we can perform a single action by different ways.it uses 2 concepts such as method overloading and method over riding.
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilising the method's name.
the method over riding concepts uses the key word 'extends'.
We can extend a class by using the extends keyword in a class declaration after the class name and before the parent class.
public class ParentClass {
}
and we define child class like
public class ChildClass extends ParentClass {
}
// example of extending a class
class B {
int x = 0;
void f1 () { x = x+1;}
}
class C extends B {}
public class Test1 {
public static void main(String[] args) {
B b = new B();
b.f1();
System.out.println( b.x ); // prints 1
}
}
// example of extending a class, overwriting a method
class B {
int x;
void setIt (int n) { x=n;}
void increase () { x=x+1;}
}
class C extends B {
void increase () { x=x+2;}
}
public class Test2 {
public static void main(String[] args) {
B b = new B();
b.setIt(2);
b.increase();
System.out.println( b.x ); // prints 3
C c = new C();
c.setIt(2);
c.increase();
System.out.println( c.x ); // prints 4
}
}

Related

Inheritance in java(subclass of a subclass)

say we have three classes: class a , class b , class c;
class b inherits class a , if we define that class c inherits class b(which inherits class a) will the code give an error .If not the can we say that class c inherits class a;
in all i ask that can there be a subclass of a subclass??
In short, yes, you could definitely have a "chain" of inheritance. When you have a class A that inherits another class B, then it doesn't matter whether class B inherits from another class.
Though, you should keep in mind that a class is not able to inherit from multiple classes (it would throw a compiler error). Multiple inheritance in Java is achievable through the use of interfaces.
Yes, Multilevel inheritance refers to a mechanism where one can inherit from a derived class, thereby making this derived class the base class for the new class.
for example
Class A
{
public void methodA()
{
System.out.println("Class A method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
Class C extends B
{
public void methodC()
{
System.out.println("class C method");
}
public static void main(String args[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}

I want to check if my output is correct. And, more details on this 'getClass()' method

I just started Java, and I came across this question. I am not sure if my output is the correct one. I also want more details on the 'getClass()' method in this context, since 'Orc' and 'Unicorn' do not inherit from the same class.
abstract class Creature {
public abstract void makeNoise( );
}
class Monster extends Creature {
public void makeNoise( )
{
System.out.println("Raaa!");
}
}
class Orc extends Monster { }
abstract class Myth extends Creature { }
class Unicorn extends Myth {
public void makeNoise( )
{
System.out.println("Neigh!");
}
}
Unicorn x = new Unicorn( );
if (x instanceof Myth) {
System.out.println("myth");
}
else {
System.out.println("not myth");
}
x.makeNoise( );
Orc y = new Orc( );
if ( x.getClass( ) == y.getClass( ) ) { //I need more explanation on this 'getClass()' method
System.out.println("yes");
}
else {
System.out.println("no");
}
y.makeNoise( );
My output is:
myth
Neigh!
no
Raaa!
Is it correct?
Last question:
Is an object of a subclass an instance of the parent class?
Your code works fine and the output also correct.
Last question:
Is an object of a subclass an instance of the parent class?
to get the clarity on the above question, you need to learn inheritance concept.
Please consider the following code . I have explained in the comments
class Super {
public void test() {
System.out.println("From Super Class TestMethod");
}
}
class Sub extends Super {
public void subTest() {
System.out.println("From the Sub Class Test ");
}
}
public class SubSuperCheck {
public static void main(String[] args) {
Sub s = new Sub();// when JVM find this, it will create the memory for
// the
// two methods test() from Super class and subTest()
// from Sub Class
// if the reference(Sub s) is also the Sub then we
// can access the two methods(test() and subTest())
// if the reference(Super s) then we are able to
// access the Super class method only.
System.out.println(s.getClass());// getClass() method of Object class
// will return the the class name
// with which we created the object
// here we have created the the
// class with Sub. So that we will
// get the out put as Sub
s.subTest();// Sub class method
s.test();// Super class method
// if we create in the following way
Super s2 = new Sub();
// then we are able to access the Super class method only
s2.test();// Okay
s2.subTest();// we will get compilation error--The method subTest() is
// undefined for the type Super
}
}

How to initialize a protected final variable in a child class of an abstract parent in Java?

I tried this:
class protectedfinal
{
static abstract class A
{
protected final Object a;
}
static class B extends A
{
{ a = new Integer(42); }
}
public static void main (String[] args)
{
B b = new B();
}
}
But I got this error:
protectedfinal.java:12: error: cannot assign a value to final variable a
{ a = new Integer(42); }
^
1 error
How to work around this problem?
Some people suggested here to use a constructor but this works only in some cases. It works for most objects but it is not possible to reference the object itself from within the constructor.
static abstract class X
{
protected final Object x;
X (Object x) { this.x = x; }
}
static class Y extends X
{
Y () { super (new Integer(42)); }
}
static class Z extends X
{
Z () { super (this); }
}
This is the error:
protectedfinal.java:28: error: cannot reference this before supertype constructor has been called
Z () { super (this); }
^
One could argue that it does not make much sense to store this kind of reference, because this exists already. That is right but this is a general problem which occurs with any use of this in the constructor. It is not possible to pass this to any other object to store it in the final variable.
static class Z extends X
{
Z () { super (new Any (this)); }
}
So how can I write an abstract class, which forces all child classes to have a final member which gets initialized in the child?
You have to initialize A.a in its constructor. Subclasses will use super() to pass initializer to A.a.
class protectedfinal {
static abstract class A {
protected final Object a;
protected A(Object a) {
this.a = a;
}
}
static class B extends A {
B() {
super(new Integer(42));
}
}
public static void main (String[] args) {
B b = new B();
}
}
You cannot use this until superclass constructors were called, because at this stage the object is not initialized, even Object constructor hasn't run at this point, therefore calling any instance methods would lead to unpredictable results.
In your case, you have to resolve circular reference with Z class in another way:
Z () { super (new Any (this)); }
Either use a non-final field or change class hierarchy. Your workaround with instance method super(new Any(a())); would not work for the same reason: you cannot call instance methods until superclass constructors were run.
In my personal oppinion, your problems hints towards a flaw in design.
But to answer your question. If absolutly necessary, you can change final fields in java using reflection.
And if everything fails, you can still utilize sun.misc.unsafe.
But I strongly discourage you from doing so, since it potentially kills your vm.
My work around so far is to use methods instead of final members:
class protectedfinal
{
static abstract class AA
{
protected abstract Object a();
}
static class BB extends AA
{
#Override
protected Object a() { return this; }
}
public static void main (String[] args)
{
AA a = new BB();
System.out.println (a.a());
}
}
But I would like to use final members, because I think accessing a final member is faster than calling a method. Is there any chance to implement it with final members?

how does the call to overriden methods take place in case of dynamic dispatch

class a extends b {
void h() {
System.out.println("class a");
}
public static void main(String[]args) {
b x = new a();
c y = new b();
c z = new a();
x.h(); //output class a
y.h(); //output class b
z.h(); //output class a
}
}
class b extends c {
void h() {
System.out.println("class b");
}
}
class c {
void h() {
System.out.println("class c");
}
}
Whats is the precedence in which it checks which method to call. I am confused as to how the JVM decides which method to call when I use dynamic dispatch. The output in this case is
class a
class b
class a
and when I remove the overridden method from class a the output is
class b
class b
class b
The class used depends on the instantiated type. So if you have an instance of class a (via new a()), then whether the declared variable is of type a, b, or c does not matter for the purpose of which definition of h() is invoked (it will always invoke a.h()).
However, where the declared type does matter is in when choosing an overloaded method. If you have a subclass that overloads an overridden method, then when invoking from a variable declared as the parent class, you will never use the overloaded method. If using a variable declared as being of the subclass, then it will use the overloaded method as appropriate.

Calling An Inherited Class Method From Java

In Python, class methods can be inherited. e.g.
>>> class A:
... #classmethod
... def main(cls):
... return cls()
...
>>> class B(A): pass
...
>>> b=B.main()
>>> b
<__main__.B instance at 0x00A6FA58>
How would you do the equivalent in Java? I currently have:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
#Override
public void show(){
System.out.println("B");
}
}
I'd like to call B.main() and have it print "B", but clearly it will print "A" instead, since "new A()" is hardcoded.
How would you change "new A()" so that it's parameterized to use the class it's in when called, and not the hard-coded class A?
Static methods in java are not classmethods they are staticmethods. In general it is not possible to know which class reference the static method was called from.
Your class B does not have a main method and static methods are not inherited.
The only way I can see this happening is to find whatever is calling A.main( String[] arg ) and change it to call B.main instead.
B.main:
public static void main( String[] arg ) {
new B().run();
}
How is your program started? Is there a batch file, shortcut, etc? Something you can change? Where does A.main get called?
I think this isn't possible. Here's why:
In Java, the implementation of a method is determined by the instance's run-time type. So, to execute B.show(), you need to have an instance of B. The only way I could see to do this, if the method that constructs the instance is supposed to be inherited, is to use Class.newInstance() to construct an instance of a type that's not known at runtime.
The problem with that is that within a static method, you have no reference to the containing class, so you don't know whose newInstance method to call.
Why do you want to do this, though? There may be some better way to achieve whatever it is you want to achieve.
In your example I wouldn't put your main method inside of A. This is setup as the entry point into the system (you can't be in B if you are specifically entering into A).
In the example below I created class A, B, and C. Class C instantiates A and B and runs them. Notice that in C I created an A, a B, and another A that I instantiate as a B. My output is:
A
B
B
Hopefully this makes sense.
public class A {
public void show(){
System.out.println("A");
}
public void run(){
show();
}
}
public class B extends A {
#Override
public void show(){
System.out.println("B");
}
}
public class C {
public static void main(String[] args) {
A a = new A();
B b = new B();
A anothera = new B();
a.show();
b.show();
anothera.show();
}
}

Categories