Call a child class method from a parent class object

后端 未结 7 548
星月不相逢
星月不相逢 2020-12-06 09:35

I have the following classes

class Person {
    private String name;
    void getName(){...}}

class Student extends Person{
    String class;
    void getCl         


        
7条回答
  •  眼角桃花
    2020-12-06 10:18

    class Car extends Vehicle {
            protected int numberOfSeats = 1;
    
            public int getNumberOfSeats() {
                return this.numberOfSeats;
    
            }
    
            public void  printNumberOfSeats() {
              //  return this.numberOfSeats;
                System.out.println(numberOfSeats);
            }
    
    
        } 
    
    //Parent class
    
      class Vehicle {
            protected String licensePlate = null;
    
            public void setLicensePlate(String license) {
                this.licensePlate = license;
                System.out.println(licensePlate);
            }
    
    
       public static void main(String []args) {
           Vehicle c = new Vehicle();
    
          c.setLicensePlate("LASKF12341"); 
    
    //Used downcasting to call the child method from the parent class. 
    //Downcasting = It’s the casting from a superclass to a subclass.
    
          Vehicle d = new Car();
          ((Car) d).printNumberOfSeats();
    
    
       }
       }
    

提交回复
热议问题