I want to override the methods in the internal class in Java.

Asked 2 years ago, Updated 2 years ago, 33 views

Is it possible to do the following in Java?

abstract class A<Textends B>{
  Tbaz;

  A(){}

  String getFoo() {
    return this.baz.b1;
  }

  classB{
    String b1;
    US>B(){
      This.b1 = "bar";
    }
  }
}

class A'extends A<B'>{
  A'(){
    This.baz = new B'();
  }

  String getBar() {
    return this.baz.b2;
  }

  class B'extends B{
    String b2;
    US>B'(){
      super();
      This.b2 = "bar";
    }
  }
}

US>class Main {
  public static void main(String[]args) {
    A'a = new A'();
    System.out.println(a.getFoo()+a.getBar()); // out "foobar"
  }
}

Also, is it possible to override class B's method in class B'

java

2022-09-30 19:39

2 Answers

Yes, but the sample code already has an error in the declaration section of the A class.

Error because internal class cannot be found when declaring A (the definition line of Class A itself is not inside the A class = Class B is out of scope)

class A<Textends B>{//B not accessible
    classB{}
}

The following is fine.

class A<Textends A.B>{
    classB{}
}


2022-09-30 19:39

I haven't read much of the code's intentions, but the compilation goes through below.

Using Java Classes
http://www.ne.jp/asahi/hishidama/home/tech/java/class_use.html

abstract class A<Textends A.B>{
  Tbaz;

  A(){}

  String getFoo() {
    return this.baz.b1;
  }

  classB{
    String b1;
    US>B(){
      This.b1 = "bar";
    }
  }
}

classAdash extensions A<Adash.Bdash>{

  US>Adash(){
    This.baz = new Bdash();
  }

  String getBar() {
    return this.baz.b2;
  }

  class Bdash extensions A.B {
    String b2;
    US>Bdash(){
      super();
      This.b2 = "bar";
    }
  }
}

/**
 * Run From Here
 */
public classprog {
    public static void main(String[]args) {
        Adasha = new Adash();
        System.out.println(a.getFoo()+a.getBar()); // out "foobar"
    }
}

Live demo on wandbox


2022-09-30 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.