简体   繁体   中英

Methods and subclass in java

I have a class called Movie with its data and a method that prints it on the screen. I have another class MovieOV which is a class inheriting from Movie. Additionally, MovieOV has a new field that also saves the language. How can I modify the method so that it also prints the language if it is MovieOV?

You can override the same display method in the subclass, as the one in the base class will be overriden by the method

/* 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. 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. You can reference instance variables of Movie class by using this keyword.

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