Method not found in derived class inherited from abstract class [duplicate] - java

This question already has answers here:
Superclass reference not able to call subclass method in Java
(2 answers)
Closed 2 years ago.
abstract class superclass {
public abstract void method();
}
class subclass extends superclass {
public void method() {
//do something
}
public void newMethod() {
//do something
}
}
public class mainclass {
public static void main(String[]args) {
superclass abc = new subclass();
abc.method();
abc.newMethod(); //cannot find symbol error
}
}
In the above example, can new methods be not written in the derived class of an abstract class? If I do that, it raises an error.

When extending a Superclass you can in fact add more methods. Hoevery in this case you assign your new subclass() to a variable of the type superclass which means that you will only have access to the methods wich are a part of that type. In this case that's only method(). If you want to use both methods you should write instead:
subclass abc = new subclass();
or cast it on demand:
((subclass) abc).newMethod();

Related

Explain the output of below java code [duplicate]

This question already has answers here:
“overriding” private methods with upcasting call in java
(1 answer)
Overriding private methods in Java
(10 answers)
Closed 5 years ago.
Can anybody explain why output to below question is "A.test" ?
class A {
private void test(){
System.out.println("A.test");
}
public void mytest(){
this.test();
}
}
class B extends A{
protected void test(){
System.out.println("B.test");
}
}
public class Test{
public static void main(String[] args) {
A a = new B();
a.mytest();
}
}
The test() method of class A cannot be overridden by class B, since it is private. Therefore this.test(); invokes A's test() method even though it is executed on an instance of class B.
Super class can invoke the methods of the sub class without using typecasting, without using reflection and without using a reference other than this only if they are overridden.
In your case A a = new B(); , object of B is created which has both the behaviours private void test() as inherited by super class A as well as protected void test() as added by B. The reason for both the methods being there and not just one is that due to the acess modifier being private the method is not visible in subclass scope. Hence it can not overriden and adding the method with same name just simply adds another method.
As there is no run time polymorphism in this case hence compile time target method is resolved and method defined in A is invoked.
If in case you would have overriden the mytest in B and from the overriden mytest you would have made a call to test then method in B would have been invoked. This is easy to understand as any method of B can not see any private method of its super class.

creating object with different reference [duplicate]

This question already has answers here:
Why do we assign a parent reference to the child object in Java?
(11 answers)
What does it mean to "program to an interface"?
(33 answers)
Closed 6 years ago.
I am so confused in this topic.
//a class (lets say B) extendes or implements another class or interface respectively
interface myInterfaceA{
int interfaceDataMember1;
int interfaceDataMember2;
void interfaceMethod1();
void interfaceMethod2();
}
class myClassA{
int parentClassDataMember1;
int parentClassDataMember2;
myclassA(){}
void parentClassMethod1(){}
void parentClassMethod2(){}
}
//case1
class B implements myInterfaceA{
int dataMember1;
int dataMember2;
B(){}
void method1(){}
void method2(){}
}
// OR case2
class B extends myClassA{
int dataMember1;
int dataMember2;
B(){}
void method1(){}
void method2(){}
}
// so in either case what is the purpose of creating the object of class B in the following way
myInterfaceA objectB = new B();
// or
myClassA objectB = new B();
1) is there any name of this procedure?
2) what (data memeber, methods, constructor ) will be loaded in objectB?
3) if all the code of class B will be loaded in the objectB then why did we give the refrece of interface or parent class?
4) is this shows polymorphism? if yes, then why?
5) in case2 will class B also inherit the constructor of myClassA
6) why the constructor of parentclass is also called whe we create child class object
1) is there any name of this procedure?
This is polymorphism.
2) what (data memeber, methods, constructor ) will be loaded in
objectB?
Every data member and method will be inherited by the objectB.
In case of interfaces, the data members are private, static, final constants. They must be initialized in the constructor. The methods must be implemented by the class B.
In case of superclasses, the data members and methods are simply inherited. You can override the methods. Variables are not polymorphic.
3) if all the code of class B will be loaded in the objectB then why
did we give the refrece of interface or parent class?
We give reference of interface or parent class so that in case of multiple subtypes, we can have a single method that accepts supertype instead of creating multiple methods. This reduces lines of code and makes the code readable.
4) is this shows polymorphism? if yes, then why?
This shows polymorphic behaviour so you don't need to bind each subtype to a different method. A single method can be written to dynamically bind all the subtypes of a single supertype.
5) in case2 will class B also inherit the constructor of myClassA
The constructor is not inherited. You must call explicitly super() if required.
6) why the constructor of parentclass is also called whe we create
child class object
It is not mandatory to call the constructor of the parentclass everytime. You may skip it if it is not required. But as a standard practice, super() is the first line of the child class constructor, so that any changes in the super class object creation does not affect child class.
Interfaces (and implementing them) only dictate what method signatures the inheriting class must have. The only thing that is 'copied', ie available as methods, are default methods since Java 8
Extending from a class (or abstract class) is a whole different story, although it also can dictate what method signatures are to be implemented by the inheriting class.
But here, all data is not copied, but available, to the calling interface.
Interfaces are used to standardise behaviour (treat dogs and birds as pets), abstract classes to standardise behaviour AND provide implementations (let budgie and cockatoo fly)
package zoo;
import java.util.ArrayList;
interface Pet {
void printName();
}
abstract class Bird implements Pet {
public void fly() {
System.out.println("I (" + getClass().getSimpleName() + ") am flying");
}
}
class Dog implements Pet {
#Override public void printName() {
System.out.println("Hans");
}
}
class Budgie extends Bird {
#Override public void printName() {
System.out.println("Jockl");
}
}
class Cockatoo extends Bird {
#Override public void printName() {
System.out.println("Zenzi");
}
}
public class AnimalSchool {
public static void main(final String[] args) {
final Dog d = new Dog();
d.printName();
final Budgie b = new Budgie();
b.printName();
b.fly();
final Cockatoo c = new Cockatoo();
c.printName();
c.fly();
final ArrayList<Pet> pets = new ArrayList<>();
pets.add(d);
pets.add(b);
pets.add(c);
for (final Pet pet : pets) {
System.out.print("\nPet is a " + pet.getClass().getSimpleName() + " and is called ");
pet.printName();
}
final ArrayList<Bird> byrdies = new ArrayList<>();
// byrdies.add(d); this will not compile, as it is not a bird
byrdies.add(b);
byrdies.add(c);
for (final Pet pet : byrdies) {
System.out.print("\nBird is a " + pet.getClass().getSimpleName() + " and is called ");
pet.printName();
}
}
}
To answer your question.
It is called polymorphism
In object B using case 1, B will be forced to implement myInterfaceA methods also your class B cannot have unimplemented methods except you declare the class as abstract thus:
class B implements myInterfaceA{
int dataMember1;
int dataMember2;
B(){}
public void method1(){
}
public void method2(){
}
//interface methods
public void interfaceMethod1(){
}
public void interfaceMethod2(){
}
}
Hence class b will have properties of the interface and that of itself as well as methods it has implemented.
Using case 2 B will however be implemented like this. (Assuming a is not an abstract class, thus it's methods will be implemented not declared like interface methods or abstract class method)
class B extends myClassA{
int dataMember1;
int dataMember2;
B(){
super();
}
public void method1(){
}
public void method2(){
}
}
notice that an explicit call may be made to the super class constructor
we give the reference to the interface/parent class because we want to have a single implementation where the super type is passed and the implementation is used for cases where there are many subtypes
Yes, it is polymorphic so that we can have different behaviours and implementations of the super type.
As i said earlier, an explicit call will be made to the super class constructor
It is standard practice to call the superclass constructor so that changes to it will not affect the subclass

Can an abstract class be instantiated? [duplicate]

This question already has answers here:
Can we instantiate an abstract class?
(16 answers)
Closed 7 years ago.
abstract class A {
public void disp() {
System.out.print("Abstract");
}
}
public class B {
public static void main(String args[]) {
A object = new A(){ };
object.disp();
}
}
I am aware that Abstract classes cannot be instantiated, but confused on this code.
Actually what this code mean ?
The subtlety here is in the "{}". It means you explicitly provide an anonymous implementation for the missing parts (the missing parts are abstract methods) of the abstract class A allowing you to instantiate it.
But there's no abstract method in A, therefore the anonymous implementation is empty.
Example showing the behaviour with at least one abstract method:
public abstract class A {
public abstract void bar();
public void disp() { System.out.print("Abstract"); }
}
public class B {
public static void main(String args[]) {
A object = new A() {
#Override public void bar() { System.out.print("bar"); }
};
object.disp(); //prints "Abstract"
object.bar(); //prints "bar"
}
}
This is called an anonymous inner class. You are not instantiating the abstract class, you are instantiating the concrete anonymous inner class which extends the abstract class. Of course, in order for this to be allowed, the anonymous inner class must provide implementations for all the abstract members of the abstract superclass … which it does in this case, because the abstract superclass has no abstract members.

Why is it said that static methods cannot be inherited? [duplicate]

This question already has answers here:
Are static methods inherited in Java?
(15 answers)
Closed 8 years ago.
I was able to run the following code:
class A
{
public static void display()
{
System.out.println("Inside static method of superclass");
}
}
class B extends A
{
public void show()
{
display();
}
}
public class staticMethodInheritance {
public static void main(String[] args) {
B b = new B();
b.display();
}
}
Now I was able to access the method display() from the instance of the class B then why is it said that static methods cannot be inherited. If I declare a method display in class B then it is said that the method in the superclass is hidden and the method in the child class is called then again isnt this the behavior that is desired when we override a method.
The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.
Static methods are inherited but cannot be overriden they can be re- defined.

Instance of an abstract class [duplicate]

This question already has answers here:
Can we instantiate an abstract class?
(16 answers)
Closed 9 years ago.
Couldy you clarify why this works:
public abstract class AbstractClassCreationTest {
public void hello(){
System.out.println("I'm the abstract class' instance!");
}
public static void main(String[] args) {
AbstractClassCreationTest acct = new AbstractClassCreationTest(){};
acct.hello();
}
}
I suppose it contradicts to the specification where we can find:
It is a compile-time error if an attempt is made to create an instance of an abstract
class using a class instance creation expression (§15.9).
You may have not noticed the difference:
new AbstractClassCreationTest(){};
versus
new AbstractClassCreationTest();
That extra {} is the body of a new, nameless class that extends the abstract class. You have created an instance of an anonymous class and not of an abstract class.
Now go ahead an declare an abstract method in the abstract class, watch how compiler forces you to implement it inside {} of anonymous class.
Notice the difference between:
AbstractClassCreationTest acct = new AbstractClassCreationTest(){};//case 1
NonAbstractClassCreationTest acct = new NonAbstractClassCreationTest();//case 2
case1 is an anonymous class definition. You are not instantiating an abstract class; instead you are instantiating a subType of said abstract class.
Here you are not creating the object of the AbstractClassCreationTest class , actually you are creating an object of anonymous inner class who extends the AbstractClassCreationTest class.This is because you have written new AbstractClassCreationTest(){} not new AbstractClassCreationTest()
You can know more about anonymous inner class from here
An abstract class cannot instantiated.
You must create an extension class extends an abstract class and so istantiated this new class.
public abstract class AbstractClassCreationTest {
public void hello(){
System.out.println("I'm the abstract class' instance!");
}
}
public class MyExtClass extends AbstractClassCreationTest() {
}
public static void main(String[] args) {
MyExtClass acct = new MyExtClass(){};
acct.hello();
}
I post this. Can be useful for you. Have a nice day

Categories

Resources