简体   繁体   English

java 中的方法和子类

[英]Methods and subclass in java

I have a class called Movie with its data and a method that prints it on the screen.我有一个名为 Movie 的 class 及其数据和一个在屏幕上打印它的方法。 I have another class MovieOV which is a class inheriting from Movie.我还有另一个 class MovieOV,它是从 Movie 继承的 class。 Additionally, MovieOV has a new field that also saves the language.此外,MovieOV 有一个新字段也可以保存语言。 How can I modify the method so that it also prints the language if it is MovieOV?如果是 MovieOV,我如何修改该方法以便它也打印语言?

You can override the same display method in the subclass, as the one in the base class will be overriden by the method您可以在子类中覆盖相同的显示方法,因为基础 class 中的显示方法将被该方法覆盖

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

class Movie{
    String movieName;
    public Movie(String movieName){
        this.movieName=movieName;
    }
    public void display()
    {
        System.out.println("Movie Name: "+this.movieName);
    }
}

class MovieOV extends Movie{
    String lang;
    public MovieOV(String movieName,String movieLang)
    {
        super(movieName);
        this.lang=movieLang;
    }
    public void display()
    {
        System.out.println("Movie Name: "+this.movieName);
        System.out.println("Language: "+this.lang);
    }
}

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        MovieOV obj=new MovieOV("Koyla (1996)","Hindi");
        obj.display();
    }
}

So as you can see I have inherited the Movie class having movieName as its instance variable and display method which displays it.如您所见,我继承了 Movie class 的 MovieName 作为其实例变量和显示它的显示方法。 When I implement the same method in base class MovieOP then display method of Movie class will be overridden and display method of MovieOP will be called.当我在基本 class MovieOP 中实现相同的方法时,将覆盖 Movie class 的显示方法,并调用 MovieOP 的显示方法。 You can reference instance variables of Movie class by using this keyword.您可以使用此关键字引用 Movie class 的实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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