How to call a subclass method inside another class, and not its superclass?

I want to call a subclass function in another class in java. How to do it?

An example is my superclass and subclass.

public abstract class a
{
  method 0;
}

class b extends a
{
   method 1;
}

There is another class call c. I want to do the following operation in class c. C is another class in a new file. But in the same package.

class c
{
   c val;
   public c
   {
      a var1 =( (b)val.method0()).method1;

   }
}

but I got an exception when starting the program, indicating that the type can not cast a for type b. Does anyone have a suggestion to get rid of this?

Here is the actual exception error I received. (I wrote the code above as a demo)

"main" java.lang.ClassCastException: classfileparser.ConstantClass classfileparser.ConstantUtf8 at classfileparser.ClassFile. (ClassFile.java:50) classfileparser.ClassFileParser.main(ClassFileParser.java:18) C:\Users\Dave\AppData\Local\NetBeans\Cache\8.2\-\run.xml: 53: Java : 1 BUILD FAILED ( : 0 )

+4
4

, , ( ), , , c.

?

0

, a, b. , d:

  a
 / \
b   d

d b , b. ClassCastException - , -, . . https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html.

method0 ConstantClass, ConstantUtf8. method1 ConstantClass ( ), , method0, ConstantUtf8 ConstantClass.

0

I think you made a declaration here of a different top-level class with a different name, which the compiler calls classname.java, so when you call class b, it is not found, because the compiler is looking for a.java if this is the name of your file. You can do what you want if class b is in the new b.java file or , you can declare class b as an inner class and call it from class c, for example: -

In class a: -

public abstract class a
{
method 0;

class b{
method 1;
}
}

In class c: -

class c extends a{// because a is abstract c extends a
a obj1 = new a();//obj1 of class a is declared
a.b obj2 = obj1.new b();//obj2 declared for class b through obj1

public c{
obj2.method(1);//call method in inner class b
}
0
source

Source: https://habr.com/ru/post/1677789/


All Articles