user4714963
user4714963

Reputation: 9

Abstract Class comp error? Java

I'm very new to Java and just trying to get the basics down. I am throwing a code with my main class objects in my abstract class and I'm not sure what to change.

public class Test {
    public static void main(String[] args) {
        m(new GraduateStudent());
        m(new Student());
        m(new Person());
        m(new Object());
    }

    public static void m(Student x) {
       System.out.println(x.toString());
    }
}

class GraduateStudent extends Student {
}

class Student extends Person {
    public String toString() {
        return "Student";
    }
}

class Person extends Object {
    public String toString() {
        return "Person";
    }
}

Upvotes: 0

Views: 82

Answers (1)

Sagar Devkota
Sagar Devkota

Reputation: 1192

Simply Change

public static void m(Student x) {
        System.out.println(x.toString());
}

to

public static void m(Object x) {
        System.out.println(x.toString());
      }

Because all child classes can be casted to parent, parents can't be casted to child

Upvotes: 1

Related Questions