0

I have seen a few references of instantiating a new object as follows, especially when using Inheritance.

Cat cat = new Animal();

However, I do not know what this concept is called. and so, I'm unable to read up on it.

I have two questions.

  1. What is this concept called?
  2. How is this possible, that, you can hold/refer to an object using a type that is different from it's original class?
saltmangotree
  • 171
  • 4
  • 11

2 Answers2

0

The basic concept in play here is inheritance. A good place to start reading about it is https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Your example is reversed — it should be

Animal animal = new Cat();

This is because the Cat class would be a specific kind of Animal — having everything needed to make an Animal object, plus some extras.

In code, this could look something like:

public class Test
{
    public static class Animal
    {
        protected String sound;
        public String getSound() { return sound; }
        public Animal() { sound = ""; }
    }

    public static class Cat extends Animal
    {
        public Cat() { super(); sound = "meow"; }
    }

    public static void main(String[] args) {
        Animal animal = new Cat();
        System.out.println(animal.getSound());
    }
}

And the result would be

meow

because the Cat object has the getSound() method from the parent Animal, but was created with its own constructor and set the data appropriately.

Matthew Read
  • 1,365
  • 1
  • 30
  • 50
0
  1. In object oriented programming world, this concept is called as inheritance.
  2. It is possible to assign a child's object to parent's reference. Err, too techie, eh? So take it this way, a Cat is a kind of Animal, but the reverse is not necessarily true. So, an Animal can be a Cat, Dog, or whatever, because cats and dogs do have properties of an animal. This is also called generalization and specialization. An Animal is a generalized category, but a Cat is a specialized category of Animals.

There are a lot of resources available on the Internet. Have a look and learn about the Object Oriented Programming paradigm. Good luck!

31piy
  • 23,323
  • 6
  • 47
  • 67