简体   繁体   中英

how to override function of class while creating its object

I searched stackoverflow and google but couldn't understand. This is my code. Class Test and class Tester are in different package and I cannot extend Test class

I want to override token() of class test in get() of class Tester

public class Test{
    private String d;
    private String f;

    Test(String d, String f) {
        this. d = d;
        this.f = f;
    }

    public String token(String a, String b) {
        String c; 
        // token() logic
        return c;
    }

}

public class Tester{

    public void get() {
        Test t = new Test (“sample1”, “sample2”);
       // get() logic
    }

}

You do it like this

Test t = new Test("abc","xyz"){
  @Override
  public String token(String a, String b) {
    // New logic here
  }      
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM