Click here to Skip to main content
15,900,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting this error:

Error:
Main.java:22: error: incompatible types: A.B cannot be converted to A
A a = new A(). new B();
^
Main.java:23: error: cannot find symbol
a.func2();
^
symbol: method func2()
location: variable a of type A
2 errors

What I have tried:

Java
import java.lang.*;
import java.util.*;

class A {
		    int a;
		    void func1()
		    {
		        System.out.println(1);
		    }
		    class B{
		        void func2()
		        {
		            System.out.println(2);
		        }
		    }
}


public class Main
{
	public static void main(String[] args) {
	    A a = new A(). new B();
	    a.func2();
	}
}
Posted
Updated 26-Nov-21 21:03pm

1 solution

B is a separate class: it has access to its containing class information, but it isn't the containing class, nor is it derived from it.
So the error message is quite right: you can't convert an B instance into an A instance and store it in an A variable.

Think about it: what would happen if you could? What if A contained a B and a C class? What type of data would be stored in the variable if you did that for both B and C instances?

Even if you could, func2 isn't a part of the A class - it's part of the B class, so you need to use a B instance (and a B variable) to access it. Again, if wyoru code compiled with a C class added, what would it call?

If you aren't sure why something doesn't work, try thinking about what could happen if it did. What problems does that bring? Ask yourself enough questions like that and you often end up understanding something a lot better!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900