Java Video Tutorial 14

Java Video Tutorial 14In this Java video tutorial I cover Polymorphism, Inheritance, Protected, Final, Instanceof and a bunch more.

These topics are not complicated, but for some reason they are normally presented in complicated ways.

Use the code that follows the video to help you gain a complete understanding of these topics. If anything isn’t 100% clear leave a comment below and I’ll help.

If you like videos like this share it

Code from the Video

ANIMAL.JAVA

// Animal will act as a Super class for other Animals
public class Animal {
	
	private String name = "Animal";
	public String favFood = "Food";
	
	// You use protected when you want to allow subclasses
	// To be able to access methods or fields
	// If you would have used private their would be no
	// way for subclasses to call this method
	// This is a final method which means it can't be overwritten
	
	protected final void changeName(String newName){
		
		// this is a reference to the object you're creating
		
		this.name = newName;
		
	}
	
	protected final String getName(){
		
		return this.name;
		
	}
	
	public void eatStuff(){
		
		System.out.println("Yum " + favFood);
		
	}
	
	public void walkAround(){
		
		System.out.println(this.name + " walks around");
		
	}
	
	public Animal(){
		
	}
	
	public Animal(String name, String favFood){
		
		this.changeName(name);
		this.favFood = favFood;
		
	}
	
}

CAT.JAVA

// Cat is a Subclass of Animal
// You create subclasses with the extends keyword
// Now Cat has all the Methods and Fields that Animal defined
// This is known as inheritance because Cat inherits all
// the methods and fields defined in Animal

public class Cat extends Animal{
	
	// You can add new fields to the subclass
	public String favToy = "Yarn";
	
	// You can add new methods
	public void playWith(){
		
		System.out.println("Yeah " + favToy);
		
	}
	
	// Here I overrode the Animal walkAround method
	public void walkAround(){
		
		// this refers to a specific object created of type Cat
		
		System.out.println(this.getName() + " stalks around and then sleeps");
		
	}
	
	public String getToy(){
		
		return this.favToy;
		
	}
	
	public Cat(){
		
	}
	
	public Cat(String name, String favFood, String favToy){
		
		// super calls the constructor for the super class Animal
		
		super(name, favFood);
		
		// We set the favToy value in Cat because it doesn't 
		// exist in the Animal class
		
		this.favToy = favToy;
		
	}
	
}

LESSONFOURTEEN.JAVA

public class LessonFourteen{
	
public static void main(String[] args){
		
		// I create a Animal object named genericAnimal
	
		Animal genericAnimal = new Animal();
		System.out.println(genericAnimal.getName());
		System.out.println(genericAnimal.favFood);
		
	
		// I create a Cat class like any other
		Cat morris = new Cat("Morris", "Tuna", "Rubber Mouse");
		
		// Print out the name, favFood and favToy
		System.out.println(morris.getName());
		System.out.println(morris.favFood);
		System.out.println(morris.favToy);
		
		// You can also create classes based on the super class
		
		Animal tabby = new Cat("Tabby", "Salmon", "Ball");
		
		// You pass objects like any other field
		acceptAnimal(tabby);
		
	}
	
	public static void acceptAnimal(Animal randAnimal){
		
		// Gets the name and favFood for the Animal passed
		System.out.println(randAnimal.getName());
		System.out.println(randAnimal.favFood);
		
		// This is Polymorphism
		// The interpreter automatically figures out what type
		// of Animal it's dealing with and checks to make sure
		// if methods were overwritten that they are called 
		// instead
		randAnimal.walkAround();
		
		// The interpreter won't find anything that doesn't 
		// originally exist in the Animal class however
		// System.out.println(randAnimal.favToy); Throws an ERROR
		
		// If you want access to fields or methods only found
		// in the Cat class you have to cast the object to
		// that specific class first
		Cat tempCat = (Cat) randAnimal;
		
		System.out.println(tempCat.favToy);
		
		// You could also cast the object directly like this
		System.out.println(((Cat) randAnimal).favToy);
		
		// You can use instanceof to check what type of object
		// you have. This results in a positive for Animal 
		// and for Cat
		if (randAnimal instanceof Cat)
		{
			System.out.println(randAnimal.getName() + " is a Cat");
		}
		
	}
	
}

27 Responses to “Java Video Tutorial 14”

  1. Pete says:

    Hello Derek,

    your videos are gorgeous!

    What’s the advantage of using the constructor of the super-class in line 42! Why not using the constructor of the child-class?

    🙂 , Pete

    • admin says:

      Thank you 🙂 You use super(name, favFood) because the fields name and favFood are in the super class. At this point I’m just demonstrating oop concepts. Later on I show you why it is better to use super classes and subclasses. If you want to know why now, look at my design patterns video tutorial. I hope that helps

  2. Lucky says:

    Derek, thanks for the video, just tell me is android development the last stage after i complete watching all of your videos.

    • Derek Banas says:

      I’m going to cover Android when I finish with Algorithms. I haven’t decided if it will come immediately because I ultimately want to design games for Android. If I think it will be easier to teach desktop game development first and then move to Android games I may do that. I may also decide to do it the other way around.

  3. AAMIR says:

    Animal tabby = new Cat(“Tabby”, “Salmon”, “Ball”);

    CAN U PLZ ELABORATE THIS.does the animal class has all the methods and fields in cat class or reverse is the case.
    here tabby holds the refrence to cat class, but is defined as Animal tabby which means it is of type animal i.e, it has all methods and fields of animal class.PLZ EXPLAIN THIS.

    • Derek Banas says:

      Yes the cat class inherits all the methods in animal and it will use them unless the cat class overwrites those classes. Because it is an animal though you’ll be able to take advantage of polymorphism

  4. Akshay says:

    Dear Tobby,

    Your videos are very nice. They are helping in my interview prep.
    Can you please explain
    Animal tabby = new Cat(“Tabby”, “Salmon”, “Ball”);
    Yes I read ur explanation above.

    But then in System.out.println(randAnimal.favToy);
    why does it throw an error??

    Thank you 🙂

  5. MSkiLLz says:

    Get video Derek but you didn’t spend much time explaining the protected access modifier. You say that it allows subclasss to access methods and fields but why would you choose protected over public? What else besides subclasses could access your methods or fields if you make it public?

    Thanks.

    • Derek Banas says:

      Sorry about that. To make it simple, protected is like private except for the fact that classes in the same package can access each other as if they were public. Does that make sense?

  6. Jimmy says:

    Hi and thank you for all your hard work. Can you explain why one would want to use Animal tabby = new Cat(); instead of Cat tabby = new Cat();? What is the benefit of mixing it up(polymorphism)?

    • Derek Banas says:

      Yes polymorphism is the reason. It is very beneficial to be able to refer to many subclasses as their super class type. As the tutorial continues you’ll see why

      • Anonymous says:

        It keeps saying my comments are awaiting moderation, and you didn’t respond to my first one so I’ll try this. My original comment: Ok, so as I watched your videos and started thinking more, I realized I don’t know as much about the difference between public, private, and protected. I looked on the internet but everything I saw compared to what I had seen you do in your code seemed to contradict eachother. Whenever I thought I understood it I just looked back at your code and realized what I thought couldn’t be right. So if you could help to clarify this I’d appreciate it alot.

        • Derek Banas says:

          Sorry about losing your comment. That happens some times for some weird reason?

          Lets say you have a class named Machine with a method named doStuff().

          If doStuff() was public, anyone could create and object of type Machine and call for doStuff to execute.

          If doStuff() was private, only methods inside the class Machine could call for doStuff() to execute.

          If it was protected only classes saved in the same package with Machine could call for doStuff() to execute.

          Does that help?

  7. Anonymous says:

    Just making sure you notice my previous comment, it says its awaiting moderation so I’m not sure what that means.

    • Derek Banas says:

      Every comment is labeled as awaiting moderation until I read it. For security reasons I can’t let people post directly to my site. Sorry about that, but I read and responded to your comment

  8. Anonymous says:

    Ok, i tried adding my email because it said my comment is awaiting moderation, and you skipped over it, so I’m gonna try again. My original comment: Ok, so as I watched your videos and started thinking more, I realized I don’t know as much about the difference between public, private, and protected. I looked on the internet but everything I saw compared to what I had seen you do in your code seemed to contradict eachother. Whenever I thought I understood it I just looked back at your code and realized what I thought couldn’t be right. So if you could help to clarify this I’d appreciate it alot.

  9. Anonymous says:

    Comment

  10. shawn says:

    thanks for this tutorial derek! i just ran into small doubt. I really didn’t understood the basics of generic constructor like you have used here “public Animal(){ }” why we have to use this ? I searched through some other sites but instead they confused me a lot as they are using some “” signs to declare generics. Can you highlight it what is it and why it is used?

  11. Sam says:

    Hi Derek,

    Thank you for the great videos. When would you use an interface vs. an abstract class ?

    Thanks

Leave a Reply

Your email address will not be published.

Google+