了解Java继承和函数创建

时间:2019-03-08 10:24:54

标签: java inheritance methods

我有一个基类,如下所示:

class BaseClass{
  //this is a base class
  // I dont want to add any generic methods here as it is 
  //extended by tens of classes
}

现在有两个特定的类扩展了该基类

class Abc extends BaseClass{

//method
  void letsGo(){
    //this method is not there in base class
  }
}
class Xyz extends BaseClass{

//method
void letsGo(){
    //this method is not there in base class
  }

}

现在我需要一个函数,该函数必须使用类似于下面的语法接受Xyz类的对象或Abc类的对象

void run (BaseClass base){
  base.letsGo() // I know it wont work 
}

并像run(object of Abc)run(object of Xyz)那样称呼它。

我该如何实现。我不想在基类中添加抽象方法,因为它被许多类扩展了

1 个答案:

答案 0 :(得分:1)

您的问题似乎是父类import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MovieProviderService { storeMovie: any[]; constructor(private http: HttpClient) { } getmovies(): Observable<any> { return this.http.get('https://sg.media-imdb.com/suggests/j/johnwick.json'); } } 将被许多子类继承,但是只有一小部分子类需要实现import { Component, OnInit } from '@angular/core'; import { MovieProviderService } from '../movie-provider.service'; @Component({ selector: 'app-movie-container', templateUrl: './movie-container.component.html', styleUrls: ['./movie-container.component.scss'] }) export class MovieContainerComponent implements OnInit { constructor(private movieService: MovieProviderService) { } ngOnInit() { let obs = this.movieService.getmovies(); obs.subscribe( (response)=>{ const data = response.json(); console.log(data);}, (error)=>{console.log(error)} ) } } 。我认为最简单的解决方案是制作一个包含方法BaseClass的中间子类,例如letsGo(扩展MediumClass),然后使BaseClassletsGo继承那。最后,使Abc方法以中间类为参数。