#Polymorphism question MOOC part 9

1 messages · Page 1 of 1 (latest)

west heron
#

I've been reading through the text and a bit confused on one thing, if you do something like
Person p = new Student(); //student extends person
you can't access any of the student methods the person class doesn't have
BUT if the student and person method have the same method like toString()
it will be overriden by the subclass?

shell finchBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
I've been reading through the text and a bit confused on one thing, if you do something like Person p = new Student(); //student extends person you can't access any of the student methods the person class doesn't have BUT if the student and person method h

When you create an object using the superclass type, you can only access the methods and fields that are defined in the superclass. If you want to access the subclass-specific methods, you need to cast the object back to the subclass type.

Example:

Person p = new Student();
Student s = (Student) p;
s.studentMethod();

Useful links:

  1. Oracle Java Tutorials - Polymorphism
  2. GeeksforGeeks - Polymorphism in Java
  3. JournalDev - Polymorphism in Java
silent karma
#

every class in Java extends Object superclass

#

which has these

west heron
#

sorry if it wasn't clear
im basically asking if the superclass and subclass have the same method it is overriden by the subclass but objects instantiated as a superclass but referencing a subclass cannot access subclass methods the superclass doesnt have

west heron
silent karma
#

every method the subclass has

#

and the superclass has given the superclass method havent been overriden

#

then u get the override ones

west heron
#

huh

#

so it can access all subclass methods

silent karma
#

yes?

#

why dont u try it

west heron
#

just tried it i got my answer it only has access to thee superclass methods but if its overriden in the subclass then it will call that method

silent karma
#

no?

#
class Animal {
    public void speak() {
        System.out.println("Speaking");
    }

    public void eat() {
        System.out.println("Eating food");
    }
}

class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Barking");
    }

    public void greet() {
        System.out.println("Greetings human");
    }
}

class Main {
    public static void main(String[] args) {

        Dog dog = new Dog();

        dog.speak();
        dog.eat();
        dog.greet();
    }
}
shell finchBOT
silent karma
#

See output

Barking
Eating food
Greetings human
shell finchBOT
silent karma
#

ofc u cant call greet on Animal animal = new Dog(); because it doesnt exist on animal just on dog

rocky jasper