Java error: class, interface, or enum expected - java

I need to know the output of this code. But it's not working. Maybe the code is wrong.
I'm still learning how to use Java, and I tried fixing this for hours but still no luck.
Here is the code:
public class A
{
public A()
{
System.out.println ("A");
}
}
public class B extends A
{
public B()
{
System.out.println ("B");
}
}
public class C extends B
{
public C()
{
System.out.println ("C");
}
}
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
}
Can anyone tell me what is wrong or missing in the code?

Put your main method in a class.
Filename : DemoClass.java
class A
{
public A()
{
System.out.println ("A");
}
}
class B extends A
{
public B()
{
System.out.println ("B");
}
}
class C extends B
{
public C()
{
System.out.println ("C");
}
}
public class DemoClass {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
}
}
Another point here is, you can have only public class in a file, so your A B and C all class can't be public in same java file.
Your java file name must be same as public class name. i.e. here DemoClass is public class so file name will be DemoClass.java
Java doc for getting started : getting started with java

For example:
public class Example {
public static void main(String...args) {
new C();
}
public static class A {
public A() {
System.out.println("A");
}
}
public static class B extends A {
public B() {
System.out.println("B");
}
}
public static class C extends B {
public C() {
System.out.println("C");
}
}
}
Also note that this might not print what you would expect. It would actually print:
A
B
C
Why? Constructors are always chained to the super class.

You can, but it is not recommended, nest your classes in a file. It is perfectly valid.
Notice in the output below that each successive child calls its parent's default constructor (super()) implicitly.
I recommend you create the files: A.java, B.java, C.java, and InheritenceTest.java.
public class InheritenceTest {
public class A {
public A() {
System.out.println("A");
}
}
public class B extends A {
public B() {
System.out.println("B");
}
}
public class C extends B {
public C() {
System.out.println("C");
}
}
public static void main(String args[]) {
InheritenceTest i = new InheritenceTest();
A a = i.new A();
B b = i.new B();
C c = i.new C();
}
}
Output:
A
A
B
A
B
C

Warning:
You shouldn't have more than 1 public classes in 1 java file, not recommended. However, it could still work if you didn't use the 'public' identifier (or by using static or inside another class). But for a starter, I would recommend you to have them all in separate files.
Error:
Your main method does not belong to any class. I propose you create another class that includes the public static void main method to test your application.
Info: keep a look at inheritance as your printings might not be what you expect. (Constructor of class B calls the constructor of A, and constructor of class C calls the constructor B which in turn calls the constructor of A).
That's why you get
A
A
B
A
B
C
*due to A() it prints A, then due to B() it prints A B and finally due to C() it prints A B C.
In your case, I would try the following:
//Filename: A.java
public class A {
public A() {
System.out.println ("A");
}
}
//Filename: B.java
public class B extends A {
public B() {
System.out.println ("B");
}
}
//Filename: C.java
public class C extends B {
public C() {
System.out.println ("C");
}
}
//Filename: Test.java
//use a Test class for testing
public class Test {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
}
}

Related

How to solve this method override and polymorphism problem that have different scope?

What will be the result of attempting to compile and run the following program?
public class Main {
public static void main(String[] args) {
A ref1 = new C();
B ref2 = (B) ref1;
System.out.println(ref2.g());
}
}
class A {
private int f(){
return 0;
}
public int g(){
return 3;
}
}
class B extends A{
private int f(){
return 1;
}
public int g(){
return f();
}
}
class C extends B{
public int f(){
return 2;
}
}
I tried it and got the answer 1, but I didn't know why.
I modified the following code:
public class Main {
public static void main(String[] args) {
A ref1 = new C();
B ref2 = (B) ref1;
System.out.println(ref2.g());
}
}
to
public class Main {
public static void main(String[] args) {
A ref1 = new C();
System.out.println(ref1.g());
B ref2 = (B) ref1;
System.out.println(ref2.g());
}
}
Its output is
1
1
I can't understand why both ref1 and ref2 are 1 regardless of whether the type is cast to B.
However, if I remove both public and private, like this
public class Main {
public static void main(String[] args) {
A ref1 = new C();
B ref2 = (B) ref1;
System.out.println(ref2.g());
}
}
class A {
int f(){
return 0;
}
int g(){
return 3;
}
}
class B extends A{
int f(){
return 1;
}
int g(){
return f();
}
}
class C extends B{
int f(){
return 2;
}
}
The output becomes 2.
I wonder if this has something to do with private and public too?
My understanding is:
ref1 is of class A and refers to class C.
The superclass of C is B.
The f() method in class B is private, that is, the subclass is "hiding", so it has not been "copied" to the subclass C, so it seems to be overriding, but it is actually a new method belonging to the subclass C, but it "just happens" to have the same name as the method in the parent class.
Moreover, there is no g() in class C, so g() in B is used, and the return is f() in class B.
So the result is 1.
However, if the private and public are removed, then C can override the
f() method in B, and at this time g() will be linked to the f() method of C.
Is my understanding correct?
Thank you very much.

What does makes those methods calls returns those values?

I need to write what is the output of those methods calls.
My answer was:
I i = new A();
i.m(b);
My answer: m_IB because I doesn't have any method with a B type so I went down to class A which implements I. A doesn't also have any methods with parameter B but it extends I.IImpl which has a method with m(B b) that prints m_IB.
I j = new B();
j.m(b);
My answer: m_BB becuase again I doesn't have any method with a B type so I went down to class B because I j = new B() and it has a m(B b) which print m_BB.
interface I {
public void m(A a);
class IImpl {
public static void m(B b) { System.out.println("m_IB"); }
}
}
class A extends I.IImpl implements I {
public void m(A a) { System.out.println("m_AA"); }
}
class B extends A {
public void m(A a) {
super.m(a);
System.out.println("m_BA");
}
public static void m(B b) { System.out.println("m_BB"); }
}
public class Interfac {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.m(b); System.out.println(); // m_IB
I i = new A();
i.m(b); System.out.println(); // m_AA
I j = new B();j.m(b); // m_AA m_BA
}
}
Both of my answers are wrong and the correct output is m_AA for i and m_AA m_BA for j.
I can't understand why I get this output even if I'm calling a method with a type B.
Both of the correct answer are calling a m(A a) methods.
Your interface provides this method:
public void m(A a);
And your j is declared like this:
I j = new B();
So, yes, it's an instance of B, but it is declared as an I, meaning, when you call that method, it calls the method provided by the interface, not the overloaded one.
So, in class B it takes the method that is provided by the interface:
public void m(A a) { // this one
super.m(a);
System.out.println("m_BA");
}
// not this overloaded one
public static void m(B b) { System.out.println("m_BB"); }
The first line of that method is:
super.m(a);
Which calls the m(a) method in the A class, which then prints: "m_AA".
Then, it prints "m_BA"

Simulate constructor overriding in Java?

Several times I thought it will be good to have overridable constructor in Java.
"Overridable" means the logic of construction can be overriden and/or extended in descending classes in the same way it is possible to override normal methods, i.e. with ability to call parent method AFTER the child.
This task can be formulated as to have a method, say, called init() which is called at construction time, but only in the last constructor of the stack.
Like:
public class InitializationOverride {
public static class A {
A() {
System.out.println("Constructor of A");
}
void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
B() {
System.out.println("Constructor of B");
}
#Override
void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
C() {
System.out.println("Constructor of C");
}
#Override
void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
new A(); // should print "Constructor of A, Init of A"
new B(); // should print "Constructor of A, Constructor of B, Init of B"
new C(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
}
The obvious way is to write
public static void main(String[] args) {
new A().init();
new B().init();
new C().init();
}
but this doesn't guarantee init() is not forgotten to call.
Is it possible to do somehow?
UPDATE
It is not known at design time, which class will be "last". It is expected, that class tree will be developed in future.
UPDATE 2
Here is the solution with reflection and constructor code requirement to call currentStage() at the end:
public class InitializationOverride {
public static class A {
A() {
System.out.println("Constructor of A");
currentStage(A.class);
}
void currentStage(Class<?> cls) {
if( cls == getClass() ) {
init();
}
}
void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
B() {
System.out.println("Constructor of B");
currentStage(B.class);
}
#Override
void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
C() {
System.out.println("Constructor of C");
currentStage(C.class);
}
#Override
void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
new A(); // should print "Constructor of A, Init of A"
new B(); // should print "Constructor of A, Constructor of B, Init of B"
new C(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
Is it possible to write simpler?
Constructors shouldn't call overridable methods. If invoking of such method is necessary the better solution is makes constructors protected and provide static factory methods:
public class InitializationOverride {
public static class A {
protected A() {
System.out.println("Constructor of A");
}
public static A newInstance(){
A a = new A();
a.init();
return a;
}
protected void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
protected B() {
System.out.println("Constructor of B");
}
public static B newInstance(){
B b = new B();
b.init();
return b;
}
#Override
protected void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
protected C() {
System.out.println("Constructor of C");
}
public static C newInstance(){
C c = new C();
c.init();
return c;
}
#Override
protected void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
A.newInstance(); // should print "Constructor of A, Init of A"
B.newInstance(); // should print "Constructor of A, Constructor of B, Init of B"
C.newInstance(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
}
Edit
More explanation: Such solution provide benefits but also drawbacks. You should to provide a contract for classes (i.e. in Javadoc) that sub-classes that extends your class should follow this standard of objects creation. Also it creates more code. The profit is that objects created in that way:
C obj = C.newInstance()
...are always fully initialized and there is no need to remember for call init() method explicite.
Remember that it also will be the only method for create object outside the class' package (constructor won't be available), but inside same package constructor will be still available (protected methods are available inside same package)
In Java, when child class is instantiated, default constructor of parent class is always invoked (unless any other constructor is specified). Now, if you need to have a common code that needs to be executed for all the classes, it's recommended to put it in constructor. However, if you want something to be executed only in the last class in the hierarchy then (a) you can write it into the last constructor itself or (b) write an initialisation block, below example demonstrates this:
public class Test extends Test2{
public Test(){
System.out.println("In test");
System.out.println("Init last");
}
{
System.out.println("Init");
}
public static void main(String[] args) {
new Test();
}
}
class Test2{
public Test2(){
System.out.println("In test 2");
}
}
Just change your a class constructor like this, each object init method will call by calling this.init(), you required to change just most upper class constructor.Because at time of object creation parent class constructor will definitely call
public class Test {
public static class A {
public A() {
this.init();
}
void init() {
System.out.println("Called in A");
}
}
public static class B extends A {
#Override
void init() {
System.out.println("Called in B");
}
}
public static class C extends B {
#Override
void init() {
System.out.println("Called in C");
}
}
public static void main(String[] args) {
new A(); // should "Called in A" printed
new B(); // should "Called in B" printed
new C(); // should "Called in C" printed
}
}
Use super.init() for this to call root parent class init() .

Suppose there are 2 classes A and B, is it possible to create an object of A in B and of B in A?

Class A
{
B b1=new B();
}
Class B
{
A a1=new A();
}
I'm talking about something like this? Is it possible?
Yes, you can. The following compiles just fine:
class A {
B b1 = new B();
public A() {
System.out.println("A constructor");
}
}
class B {
A a1 = new A();
public B() {
System.out.println("B constructor");
}
}
public class HelloWorld {
public static void main(String []args) {
A a0 = new A();
System.out.println("Done");
}
}
However, as shown in the output, it's generally a bad idea:
Exception in thread "main" java.lang.StackOverflowError
at B.<init>(HelloWorld.java:8)
at A.<init>(HelloWorld.java:3)
at B.<init>(HelloWorld.java:8)
at A.<init>(HelloWorld.java:3)
at B.<init>(HelloWorld.java:8)
:
at A.<init>(HelloWorld.java:3)
at B.<init>(HelloWorld.java:8)
at A.<init>(HelloWorld.java:3)
at B.<init>(HelloWorld.java:8)
The fact that construction of an A tries to create a B, and construction of a B tries to create an A, means that you'll get caught in infinite regress, eventually running out of stack space.
You can safely have two objects refer to each other but it's generally done after the construction phase, something like:
class A {
B b;
public A() {
System.out.println("A constructor");
}
public void setOther(B bx) {
System.out.println("A linker");
b = bx;
}
}
class B {
A a;
public B() {
System.out.println("B constructor");
}
public void setOther(A ax) {
System.out.println("B linker");
a = ax;
}
}
public class HelloWorld{
public static void main(String []args){
A a0 = new A();
B b0 = new B();
a0.setOther(b0);
b0.setOther(a0);
System.out.println("Done");
}
}
The output of that shows:
A constructor
B constructor
A linker
B linker
Done

Two questions on inner classes in Java (class A { class B { } })

Sorry for the bad title, but I couldn't think of a better one.
I'm having a class A and a class B which is kind of a sub class of A, like so:
(Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?)
class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
B b = a.new B();
A c = ??? b ??? // get "a" back
}
}
From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.
Second one:
class A {
void print() {
System.out.println("This is class A.");
}
class B {
void print() {
// <--- How to access print() of class A (like this.A.print() or smth)?
System.out.println("This is class B.");
}
}
}
You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.
Thanks in advance. :)
There doesn't seem to be a way to access the outer class from outside. But you can do it like this:
class A {
int i = 0;
class B {
final A outer = A.this;
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = b.outer // get "a" back
}
}
ClassName.this will be the instance of the outerclass associated with the instance of an inner class.
You can access it with the ParentClass.this syntax from within the inner class.
e.g.
public class Outter
{
class Inner {
public Outter getOutter()
{
return Outter.this;
}
}
public Inner getInner(){
return new Inner();
}
}
class Runner{
public static void main(String[] args){
Outter out = new Outter();
Outter.Inner inner = out.getInner();
System.out.println(inner.getOutter().toString());
}
}
[Edit: My answer is appropriate for C# programmers, but I can't guarantee that its applicable to Java.]
B is an inner class, not a subclass of A. Additionally, B does not hold an instance of A, so your code as is cannot return any instance of A.
You need to restructure your classes as follows:
class A
{
public class B
{
public A Parent;
public B(A parent)
{
this.Parent = parent;
}
}
}
Now your B class has a field 'Parent' which returns its parent. You can use these classes as follows (this is C# syntax, because I don't know if Java has a different syntax for instantiating inner classes):
public static void Main(String[] args)
{
A parent = new A();
A.B child = new A.B(child);
A backToParent = child.Parent;
}
Of course, creating your B class in this way seems little funny: technically, you can pass in any parent. It would probably be better to rewrite your A class with a method which returns a B:
class A
{
public class B
{
public A Parent;
public B(A parent)
{
this.Parent = parent;
}
}
public B getChild()
{
return new B(this);
}
}
public static void Main(String[] args)
{
A parent = new A();
A.B child = A.getChild();
A backToParent = child.Parent;
}
this seemed to work for me
class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = (A)b.getClass().getDeclaredField("this$0").get(b);
}
}

Categories

Resources