Kilobolt
  • Home
  • Tutorials
    • Game Development Tutorial >
      • Unit 1: Beginning Java >
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I >
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II >
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development >
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake) >
      • Unit 1: Building the Game >
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial >
      • Unit 1: Writing Basic Android Apps >
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • New Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 1-10: Inheritance, Interface

9/16/2012

47 Comments

 
Picture
Welcome to Day 10, Unit 1's penultimate lesson! 

This is the beginning of the end of the Basic Java unit.
With that said, you will still be learning Java throughout the future Units, so keep your minds open and ready to learn!

In this lesson, we will be discussing inheritance and interfaces (not in extensive detail, as they will come up frequently in future Units and it is easiest to understand them as you manipulate them yourself). 

Since this lesson is the culmination of the previous lessons in the Unit, we will be applying much of what we learned previously.

If you need to refresh your memory, refer to the previous lessons!

Let's get started!

Lesson #1-19: Interfaces

If you've ever seen highly functional Java code, you might notice something like this in the class declaration: 
 public class ClassName implements InterfaceName {
... //implemented methods
}
This line of code creates a class named ClassName and declares that it implements the interface named InterfaceName.

Yeah, that's quite a mouthful... so you can think of it this way.

An interface is a collection of abstract (meaning that it's not really used, but it's just there as a reference) methods and constants that define a group. 

If a class implements this interface, then it chooses to take on all the abstract methods and constants.

For example, let's say we have an interface called Human as below: 
 public interface Human {

public void eat();
public void walk();
public void pee();

}
The interface is some thing of a contract. If we create an interface, we are telling people, "Hey, you can be a Human if you do the following..."

Notice that an interface does not have method bodies. Instead, we simply declare what methods we need for something to be "Human", and we leave them blank. Each implementation of Human can choose how they want to approach the eat, walk and pee methods.

Here's an example:
I am implementing Human (that is, accepting its three requirements) in the class King:
 public class King implements Human {

public void eat() {
System.out.println("The King eats.");
}

public void walk() {
System.out.println("The King walks.");
}

public void pee() {
System.out.println("The King urinates.");
}
}
When class King implements interface Human, the class is basically saying, "I will eat, walk, and pee. Please make me Human."

In other words, King is saying that, first and foremost, he is Human.

When you implement an interface in a Class, you must implement (or finish) everything you have stated in the interface. That means the King cannot remove the pee() method from his Class because he is, after all, only human.

You can add as many Interfaces to King as you want, such as "Male" and "Royalty". Then, you can use the King object in any method that requires a King or Human or Male or Royalty input, such as:
 // You can pass in a King object into this method.
public void doSomething(Human h) {
// do something
}
This is called polymorphism. You will see the power of polymorphism throughout this tutorial series.


Lesson #1-20: Inheritance

This is a very similar topic to interfaces.

The key difference is that inheritance deals with two classes, not a class and an interface.
Another key difference is that inheritance uses the keyword "extends" rather than "implements."

So how is "extends" different from "implements?"

Recall that when you implement an interface, you must take all the abstract qualities of the interface and implement it into the Class that is implementing it.

Not so when a class extends another class, which we refer to as a Superclass, and the extending class is called a subclass.

A class is a blueprint for objects, as I have repeated over and over again.
A superclass is a blueprint for other classes.

In inheritance, we take an abstract concept, like Phone, and create a class which will hold all the shared properties of all Phones. Then, we can use this as a blueprint to create more specialized objects, such as the iPhone class or the GalaxyS class.


Let's have a look at an example: 
 // This is the 'generic' superclass

class Phone {

// Phone class variables
int weight = 10;
int numProcessingCores = 4;
int price = 200;
boolean turnedOn = false;

public void togglePower() {
// turnedOn is now its opposite (true becomes false, and vice versa)
turnedOn = !turnedOn;
}
}
This superclass holds all the information that all phones should have, such as weight, number of cores, price and etc. Using this superclass, we can create a subclass, which will (this is key) ADD ITS OWN UNIQUE PROPERTIES to the GENERIC properties described in the superclass (meaning that iPhone below will have all the methods and variables in the Phone method and also its own methods and variables): 
 public class iPhone extends Phone {

boolean hasAppleLogo = true;
String color = "black";

void adjustPrice() {
if (hasAppleLogo) {
// Although we did not declare a price variable in this class
// we have inherited a copy of it from the Phone class.
price += 4500;
}
}
}
Now the class iPhone will be able to use all the methods and constants defined in the superclass Phone... and add its own methods (like adjustPrice()) 

Now the class iPhone will be able to use all the methods and variables defined in the superclass Phone... and add its own methods (like adjustPrice()) 

Polymorphism also works with inheritance.

Let's say we have a Hammer class:
 public class Hammer {

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

}
Its destroy method can destroy any Phone, and any other Object that extends Phone. Here's how you might do that.
 public class Hammer {

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

public static void main(String[] args) {
Hammer h = new Hammer(); // Create new hammer object
Phone phone = new Phone(); // Create new Phone object
iPhone phone2 = new iPhone(); // Create new iPhone object

h.destroy(phone); // Destroy Phone object
h.destroy(phone2); // Destroy iPhone object (POLYMORPHISM!)
}

}
The destroy method does not have to be static, because we are using an instance of the Hammer class, named h, to call the destroy method. If we didn't want to create a specific Hammer to destroy things, we would make the destroy method static, and call:

Hammer.destroy(...);

Not an extremely long lesson, but this is a very important one. Read through it thoroughly!
One more thing...

If each of you told your friends about this tutorial and asked them to like us on Facebook, it would help us out tremendously. 

Take the time to support Kilobolt!  :D
Picture
Go to Day 9: More on Looping
Go to Day 11: Threads and Graphics
47 Comments
taoshi link
11/5/2012 11:37:21 am

Great site!!! Im learning Java in college but Im want to be a game developer on my own and this site is just out of the planet XD
I've download Tumbl in my SGA already ;) and I'll share this site with the students.

Keep it up!

Reply
James C.
11/6/2012 04:42:12 pm

Thank you so much! :)

Reply
Will
11/8/2012 12:34:09 pm

When you said in Day 10: "When you implement an interface in a Class, you must define everything you have defined in the interface. That means the King cannot remove the pee() method from his Class because he is, after all, only human."

It doesn't mean that you have to implement every method or function, right? I'm use to program for .NET so Java is not new in a way but still just got to ask in this one :) and GREAT lessons, very simple and even expert developers can get lots of things from this posts

Reply
James C.
11/8/2012 01:36:46 pm

If you do not implement it, you will get an error saying that you must implement unimplemented methods.

You could always call the superclass' method in these implementations, however.

Reply
Reece
11/16/2012 05:18:59 pm

Another good lesson. Thank you!

Reply
Justin
11/25/2012 07:51:46 am

if (hasAppleLogo == true){

price += 450 // LOL!!

}

// I'd like to chip in a few lines...

else if ((hasAppleLogo == true) && (isSModel == true)){

price += 650

}

else{

System.out.print.ln("This phone is reasonably priced and thus must not be an iPhone")

}

Reply
Chris Vetrano
1/13/2013 07:24:49 am

I wish you explained more thouroughly how we could construct this using eclipse and mess around with classes, super classes and implements...

Otherwise, this whole tutorial has been great!

Reply
magento website developer link
7/10/2013 09:10:19 pm

I think that your viewpoint regarding "Java developer" is deep, it’s just well thought out and truly incredible to see someone who knows how to put these thoughts so well. Good job I read your post and I found it amazing .Your thought process is wonderful.

Reply
DVendy
2/22/2013 10:55:02 pm

if (hasAppleLogo == true){

price += 450

}

//I see what you did there., :D

Reply
Djiango
3/6/2013 07:29:05 pm

How do I call these? How do I get it to print out "The king eats"?
Same for the Iphone example, let's say I put a print in at the adjustPrice method, how do I make it run and print the output!
What to write in the main callback?

Reply
shub
9/24/2013 06:17:28 pm

for that you have to write the 'main' method, from there you can call methods like iphone and make it run.
your program WILL not run without a main method!!

Reply
Joshua Ospina
3/26/2013 04:14:29 am

Hey. Keep up the good work. I just can't wait to make my game.

P.S. I am still paying attention to your lessons.

Reply
James Anderson
4/14/2013 06:52:08 pm

Why you put [] after args instead of after String in main method?

Reply
James C.
4/21/2013 12:16:30 pm

It does the same thing.

Reply
Professional wordpress website developer link
7/10/2013 09:07:44 pm

I am very glad that I find your regular post "Website developer". Which seems to be very important and it made good time pass for me. I will always give a nice thrust look in to you from my bookmark feed. I don’t actually comment and don’t like to spend time in typing the comment.

Reply
Haseo
10/23/2013 09:08:48 pm

Hi, very well written and understandable article.
Thanks for it.

But I have one question: Is the extended class Class Iphone?

Reply
Miles
12/16/2013 08:41:59 am

Thank you for all the tutorials !

just some questions on this tutorial in particular,

I do understand the difference of extends and implements,

but what if you want to specify and add-on what else the king

can actually do other than what the average human can?

such as rule, startWar,

would it add under the other public voids?

like public void rule();
public void startWar();

or should it be static void?

Reply
Jim
12/28/2013 08:09:56 am

I haven't done any code in a number of years so this is a refresher for me. I used to play around with gamedev stuff as a hobby but didn't get too far. I had a basic understanding of a few languages. This is a good refresher.

Also, I laughed out loud when I got the the apple price part, perfect joke and can tell I'm at the android page. :)

Thanks

Reply
Jermaine
1/6/2014 08:59:56 pm

I didn't really fully understand this. So, what exactly is the difference between implements and extends? I tried some stuff in eclipse and I could use variables defined in either the superclass/interface no problem.

Reply
RandomHelper
2/15/2014 03:56:43 am

Implements: Uses the variables and constants in that class, and you must manipulate them all(Or call them or use them, otherwise Eclipse will have an error stating "Variable x is not used in this instance."
Extends: Uses the variables and constants in that class, and allows you to 'extend' the orignal class with the new class's methods. You will still be able to use the information like Implements does.

Reply
Skoll
2/11/2014 09:11:34 am

There's a little mistake, it should be:
"iPhone phone2 = new iPhone();"

not:"phone2 iPhone = new iPhone();" ;)

Reply
Just Me :)
2/15/2014 02:30:03 am

Great tutorial!! i just have a small doubt: why did you declare the destroy method as a boolean?

Reply
Krazy Lobster link
2/20/2014 06:51:39 am

Hello there,

I've been following this tutorial to great success so far, and everything seems crystal clear to me. However, I could not understand the lowercases... Like here:

// You can pass in a King object into this method.
public void doSomething(Human h) {
// do something
}

What is that lowercase "h" for? Is that the syntax?

Also here:

public class Hammer {

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

}

What's the "p" for?


THank you so much!

Reply
Mike
2/21/2014 06:15:13 am

This is the syntax (correct word usage?) for polymorphism. You're assigning the p for phone and the h for hammer. So every when he's defining variables it's easier to assign those variable to objects. IE: p.turnedOn = false.

Reply
Krazy Lobster
2/21/2014 09:23:07 am

Thank you very much!

Michael link
3/5/2014 07:48:16 pm

Very good site and information. Work collegue of mine wants to create a simple game and wants me to code it for him. I have vba experience but these tutorials are helping me learn a lot and also giving me transferable skills to my vba programming. Keep up the good work.

Reply
Alex
3/16/2014 08:20:22 am

I really don't get the point of anything in this part of the tutorial. What is it used for? I don't know what the point of the 'Human' part of the tutorial did. If you try to run it, it doesn't work. I might just be missing the point, but it's pretty confusing.

Also, the last part about the Hammer needed a "return false;" to be able to run. Like this:

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM!");
return false;

}

Otherwise it wouldn't let me.

Reply
Daniel
5/10/2014 11:24:22 am

The way I see it the 'human' part could be used for like a character creation, you could define what a character needs and if the player misses them out during the creation you could use the error to print a message telling them to input whatever was missing. I think.

Reply
Jaka
6/12/2014 12:18:35 am

I have a question. Would the last part really compile?
You have a method that takes Phone type
public boolean destroy(Phone p)

and than you call it with iPhone type
iPhone phone2 = new iPhone();
h.destroy(phone2);

Am i missing somethng, or is this wrong?
Thanks!

Reply
Jaka
6/12/2014 12:20:39 am

Newermind, i see my mistake. iPhone exteends Phone a couple of code blocks higher :)

Reply
Asmeer
6/17/2014 04:38:36 pm

Hello,
i have on doubt.
why the hammer method "destroy" has a return type boolean??

Thank you for providing this tutorial.

Reply
Clff
6/23/2014 05:19:22 am

I am a bit confused at one part. When I put the code in as shown, I get an error in eclipse that I must return a boolean value at

"public boolean destroy(Phone p) {"

It recommends that I put in a return false or return true beneath the

"System.out.println("BOOM!");"

Even when I do that though, I get a warning of the same nature. Has anyone ran into that ?

Reply
AngryAxolotl
6/29/2014 09:50:16 am

I have a question.
When you defined the hammer destroy method. You wrote it as:

public boolean destroy(Phone p){
}

I don't understand why you used boolean before the method. Also loving you tutorial series so far.

Reply
Aaron
7/19/2014 08:27:20 am

A couple of folks have mentioned this, there is a bug in the destroy method. You need to return a boolean value or Java will not compile.

Thanks for doing this!

Reply
Anukool
9/10/2014 08:27:49 pm

there is a mistake in 2nd line. it should be public void(Phone p)

Reply
Ronak Upadhyaya
9/16/2014 03:03:29 am

The best java tutorial I have seen on the internet. Thank you!

Reply
antonio
9/22/2014 08:32:30 am

i've tried to put this in eclispe withou success, here's the code:

public class Hammer {

public static void main(String[] args) {
Hammer h = new Hammer(); // Create new hammer object
Phone phone = new Phone(); // Create new Phone object
iPhone phone2 = new iPhone(); // Create new iPhone object

h.destroy(phone); // Destroy Phone object
h.destroy(phone2); // Destroy iPhone object (POLYMORPHISM!)
}

class Phone {

// Phone class variables
int weight = 10;
int numProcessingCores = 4;
int price = 200;
boolean turnedOn = false;

public void togglePower() {
// turnedOn is now its opposite (true becomes false, and vice versa)
turnedOn = !turnedOn;
}
}

public class iPhone extends Phone {

boolean hasAppleLogo = true;
String color = "black";

void adjustPrice() {
if (hasAppleLogo) {
// Although we did not declare a price variable in this class
// we have inherited a copy of it from the Phone class.
price += 4500;
}
}
}

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

}

Reply
antonio
9/22/2014 08:47:29 am

I've solved the "problem" by doing somethin i didn't knew i was supposed to do, which was having ONE file per class, instead of all in one file :)

So i had one file Phone, another iPhone and finally one Hammer.

But Hammer had one error, instead of:
public boolean destroy(ph_Phone p) {

it must be:
public void destroy(ph_Phone p) {

thanks.

Reply
antonio
9/22/2014 08:49:23 am

damn, i can't edit my posts, where it says ph_Phone, it's just Phone, i used that name in my project, but for the example it won't work like that of course.

to sum it up, the error is to replace boolean with void.

Slavomir
12/27/2014 01:32:06 am

I think, interface needs more explanation. I can not understand from this example, what ist good for :-( Maybe later...

Reply
zahida link
2/8/2015 03:42:31 pm

public class usingInterface implements Human {

public void eat(){
System.out.print("hello");
}
public void walk()
{
System.out.print("hello");

}
public static void main(String args[])
{
Human hum=new Human();

}

}

it giving me error when i create object of usingInterface class as well Human .
what is wrong here please tell me

Reply
Rudolf
2/10/2015 05:27:19 am

What do the errors say?

Reply
SmartAss Zombie
5/2/2015 12:19:17 am

i found out this lesson so hard i dont know why :( any help to make it easier? pls..and i am really thankful for this great tutorial

Reply
Yash
6/2/2015 05:05:25 pm

public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}

in this function destroy doesn't return any thing where as the return type is declared boolean.

Reply
Bella Strange
6/12/2015 11:11:23 am

This phone and hammer thing works for me as written (I have 3 separate class files for Hammer, Phone and iPhone), but when I added a print line to the Hammer class to show the starting price of the phones (because this was the only way to see how phone differed from iPhone), I realized phone2 was not getting a different initial price from phone. It's always $200, and does not change to $650 (or, $4700 as written with price+=4500; but I changed it to 450), although both get reduced to 0 after the hammer falls, as expected.

Somehow the iPhone class is not getting extended when it's originally called, and I can't figure out why . . . here's my code from hammer:

public class Hammer {
public boolean destroy(Phone p) {
System.out.println(p.price);
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM -> " + p.price);
return false;
}

Any ideas?

Reply
Bereshna
8/17/2016 10:35:26 pm

Hello sir, and thanks a lot for your useful material:
My Question in the Hammer class this method:
public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
that dont return boolean just it print BOOM , then why it defined as a method with return type Boolean , thanks

Reply
Walter
5/9/2017 01:06:16 pm

What´s the point in turning of the phone before hammering it ? :D

Reply



Leave a Reply.

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge. 


© 2014 Kilobolt, LLC. All rights reserved.