Can we Pass Abstract Class Object as Argument Using Polymorphism? - java

I have a class with name 'A'. A is an abstract class. And class 'B' extends class 'A'.
And I have another class 'C'. In class 'C' there's a function with name show().
I want to pass an object of class 'A' which is abstract. Is it
possible?
Or
Can we do this using Polymorphism.
If yes! then How?

I want to pass an object of class 'A' which is abstract. Is it possible?
Yes, it is. The following is valid:
abstract class A {}
class B extends A {}
class C {
public void show(A a) {}
}
Even though A is abstract, you can receive parameters of type A (which, in this case, would be objects of type B).
You cannot really pass an object of class A, though, since A is abstract and cannot be instantiated.
Can we do this using Polymorphism.
The above example actually already used polymorphism (subtyping).
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping

Pretty much the same as above answer, just elaborated with code. Naive way of telling, you cannot have abstract class name next to new operator except in case with array, as in A a[] = new A[10]; where you have still allocate Objects of concrete class for each element in Array.
abstract class A{
abstract void tell();
}
class B extends A{
void tell(){
System.out.println("I am B Telling");
}
}
public class Test{
public static void whoTold(A a)
{
a.tell();
}
public static void main(String[] args){
B b = new B();
whoTold(b);
}
}

Related

Is it possible to call a subclass specific method if only the superclass object has been initialized?

Lets deduct from a very simple example:
Class a:
public class a{
public a{}
Subclass b inherits a:
public class b inherits a{
public b{super}
public void customMethodB(){}
Subclass c inherits a:
public class c inherits a{
public c{super}
public void customMethodC(){}
Main:
public class Main{
public static void main(String[] args){
a newObject = null;
//User can now choose through input if he wants to create b or c. Lets say he creates b:
newObject = new b();
//His choice is stored in a string.
String userChoice = b;
//I now call the general object from another method for the user to interact with.
//(I have a feeling it is here my problem is).
}
userInteraction(a newObject, String userChoice){
if (userChoice.equals("b"){
newObject.customMethodB();
}
else if (userChoice.equals("c"){
newObject.customMethodC();
}
}
Here lies my problem: I can not call customMethodB nor customMethodC even though the object is created as b in main. Is this due to the parameter type being a in the userInteraction method? Would it be possible to do something like this without creating a method to pass the specific subclass type?
Your method customMethodB does not exist in your type a.
In order to call this method, you have to cast your object ( down cast is possible here )
if (userChoice.equals("b") && newObject instanceof b){
((b)newObject).customMethodB();
}

Java: Implementing an interfacing by inheriting a class

Time-appropriate greetings :)
Working in Java, I have an Interface A. All implementors of this Interface also extend class B, but B does not implement A. In a class where we use an instance of A (referenced as A), it is cast to a B Reference so that we can use a Method defined in class B. It makes sense conceptually that the Method should belong in Interface A too.
Can you think of a reason not to introduce the Method to Interface A, so that we don't have to cast it to B? Should I maybe override the Method in the subclasses and just call the super version, so that it's easier to navigate in the IDE etc?
In a class where we use an instance of A (referenced as A), it is cast to a B Reference so that we can use a Method defined in class B.
So I'm assuming you have this scenario
public void doStuff(A aType){
...
B bType = (B) aType;
...
}
If this is true, can this work?
private <T extends B & A> void example(T type){
type.aStuff();
type.doBStuff();
}
I created the following to test this.
public class Foo{
private static interface A{
void aStuff();
}
private static class B{
public void doBStuff(){
System.out.println("B stuff");
}
}
private static class AB extends B implements A{
public void aStuff(){
System.out.println("A stuff");
}
}
public static void main(String[] args) {
Foo foo = new Foo();
foo.example(new AB());
}
// method "example" already given
}
Gave me
A stuff
B stuff
Why not creating an abstract class which extends B and implements A? Assuming this class would be called C, your other classes would extend C and implement the method required by A, but will provide you with the methods available in B without casting.
I think that moving methods now would not be a good idea, maybe, at most, have B implement A (assuming you have no other classes which you haven't talked about which are dependent on the classes and interfaces you mentioned).

Polymorphism via Interface

I have one interface
public interface AA {
public void sayHello();
}
and implement it from one class
public class B implements AA {
#Override
public void sayHello() {
System.out.println("Hello !");
}
}
and a class has one method with parameter type of above interface
public class C {
public void invoke(AA aa) {
System.out.println("Invoking !");
}
}
construct them in my main class as
public class Main {
public static void main(String... args) {
B b = new B();
C c = new C();
c.invoke(b);
}
}
output at my console Invoking !.
I don't understand Polymorphism very well in case. Why invoke(AA aa) method of class C can accept instances of class B? Are all class the same by implementing the same interface?
For an example:
I have Student.java and Teacher.java classes. If they implement one interface with a single method gotoSchool(). They can pass any methods with parameter type of an interface that these two classes implemented? If so, can I assume instances of Student class and Teacher class are the same?
Please somebody help me what's wrong with my thinking? I only know that polymorphism happens when you extend same class. But I don't know about implementing an interfaces.
Why invoke(AA aa) method of class C can accept instance of class B ?
Because class B also implemented interface AA
Does all class are the same by implementing a same interface ?
Yes. It's like having an interface Animal. When your class Dog implements Animal Dog now IS-A(n) Animal. If Cat implements Animal, Cat now IS-A(n) Animal also.
I just only know about polymorphism to extends same class. But I don't know using with Interfaces.
Polymorphism is not just limited to extending a class. It also happens when you implement an interface.
In your given example with Student and Teacher class. Let's say you have an interface called SchoolGoer and your Student and Teacher implements it, now you can say that every instances of Student and Teacher IS-A SchoolGoer
You can now do something like this:
SchoolGoer aTeacher = new Teacher();
SchoolGoer aStudent = new Student();
aTeacher.goToSchool();
aStudent.goToSchool();
Since they both implemented the SchoolGoer interface, they can both do whatever a SchoolGoer does. In this case goToSchool.
It is the beauty of Inheritance. It's not polymorphysm. Simply we can define polymorphysm is "Same thing in multiple ways". Your program AA is a interface. B is a sub Class, inherite from AA interface. Therefore we can say
B is AA
In your C class invoke(AA aa) method accepting any AA type thing. So B is AA. Therefore that method accepting B class object. You can't give AA instance(Because we can't create objects using interfaces). As well as you can use Annonymous class for running that method. It is like this..
class Main {
public static void main(String... args) {
//B b = new B();
C c = new C();
c.invoke(new AA(){
public void sayHello(){
System.out.println("Annonymous class");
}
});
}
}

If a child class extend Base class Exception

I had a doubt.
Imagine If we have a class A that implements the method
For example
private void methodA(int index) throws Exception, Error {
}
And if we have a Class B that extends the first class A.
My questions is, can class B implement
private void methodA(int index) throws Exception, Error {
}
And which method will be called under which circumstance!!
Thanks
If your methods weren't declared "private", this would just be standard polymorphism. Because they're private, the rules are a bit different. The version in class A can only be called from code that's in class A. The version in class B can only be called from code that's actually written in class B (as opposed to code that class B gets by extending class A).
YES, you can implement the methodA method in class B, but, pay attention, you are not overriding it.
Your method is declared ad private so is not "visible" from extending classes.
If your intention is to make your method overridable, you need to declare it as public.
Just give it a try :)
public class Main {
public static void main(String[] args) {
Base base;
base = new A();
System.out.println(base.doSth());
base = new B();
System.out.println(base.doSth());
}
}
abstract class Base {
public abstract String doSth();
}
class A extends Base {
#Override
public String doSth() {
return "A";
}
}
class B extends A {
#Override
public String doSth() {
return "B";
}
}
I think you wonna override the super-class method, and to do this, the method on sub-class must have the same signature of super-class method.
You can call these methods in following ways:
Suppose test1 is an instance of classA, teste1.methodA(index) will execute the implementation on super-class.
Suppose test2 is an instance of classB, test2.methodA(index) will execute the sub-class method.
In classB you can invoque the super class method (if the method is notprivate), something like :
public class ClassB extends ClassA
{
...
super.methodA(index);
...
}

Do objects inherit?

I have three classes A,B and C.
I have created object of class A in class B and I have inherit class B to class C.
Do the object of class A also inherit to class C?
Can I access member functions of class A through class C?
You have used composition between A and B (B encloses an instance of A) and inheritance between B and C. So from C you can "get at" methods in B by using the super keyword. You may (depending on scope) thus also access members of A from within C, but you are not doing it directly by inheritance, as would be the case if C inherits from B and B inherits from A.
Here is a small example for your case use it,
class A
{
String varOfA="Class A";
private String locOfA="Local variable";
}
class B extends A
{
int number=20;
}
class C extends B
{
int total=number;
void show()
{
System.out.println(super.varOfA);
//System.out.println(super.locOfA); //This is a private variable variable, so it
//won't be accessed from sub class
System.out.println(total);
}
}
public class MLInhert
{
public static void main(String args[])
{
C obj=new C();
obj.show();
}
}
Please let me know if i made any mistake in this answer. Because i'm a beginner here.
Depending on the access specifiers of the variables in the class it is decided which class level variable can be accessed. See the table below:
For more info refer : http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Categories

Resources