Java With Pokemons - Object Oriented Programming

Java with Pokemons – Object Oriented Programming - J Ajendra First Edition. Could very well be the last. Copyright ©

Views 71 Downloads 0 File size 1MB

Report DMCA / Copyright

DOWNLOAD FILE

Recommend stories

Citation preview

Java with Pokemons – Object Oriented Programming - J Ajendra

First Edition. Could very well be the last.

Copyright © 2016 J Ajendra

All rights reserved. Though I wonder what one would ever achieve by copying the text from this document. Yet, for undoubtedly imaginary legal purposes and to make this book look a bit professional, I have decided to waste 3 minutes of my apparently pointless life, in drafting this page.

1

To, Aishwarya and Vivek Wishing you a very happy married life!

Table of Contents INTRODUCTION .................................................................................... 1 CLASSES AND OBJECTS ....................................................................... 2 ENCAPSULATION .................................................................................. 7 INHERITANCE ..................................................................................... 14 Protected Access Modifier .............................................................. 17 Instanceof Operator......................................................................... 22 Types of Inheritance ........................................................................ 26 Diamond Problem ........................................................................... 28 POLYMORPHISM ................................................................................. 32 IS – A Relationship .......................................................................... 32 Method Overriding ......................................................................... 33 Method Overloading....................................................................... 38 Constructor Overloading ............................................................... 41 Casting .............................................................................................. 44 ABSTRACTION .................................................................................... 46 Abstract Classes ............................................................................... 46 Interfaces .......................................................................................... 49 APPENDIX A ........................................................................................ 53 Reference Type and type of an Object .......................................... 53

INTRODUCTION Folks,

S

ince you have started reading this book, I take it that you know basics of programming and stuff like function calls and loops. If not, pick this book up after you are a bit familiar with all that. OOP is a fascinating topic and sadly, most of the explanations and examples available on internet are a tad boring. Trust me, I learned from those and at time, fell asleep. So this is a humble attempt to make learning interesting. Thanks to amazing yet a bit buggy game by Niantic, the Pokemon craze has taken the world by storm. If by any chance, you have been leaving under the rock and haven't heard of PokemonGo or Pokemons for that matter, please feel free to play the game for few days. Try to watch a couple of Pokemon episodes as well! (PS. I prefer Indigo league) Anyway, we are about to dive into the world of OOP with the help of these imaginary creatures. I am taking the liberty of assuming that you are familiar with the following concepts: 1. 2. 3. 4. 5. 6.

Basic Classes & Objects Primitive Data Types Constructors Function calls Loops Other procedural programming concepts not related to OOP.

Also, this book covers the most fundamental topics related to OOP. Some interesting concepts like covariant returns or Constructor chaining are skipped due to sheer boredom and laziness on author’s part. Off we go!

1

CLASSES AND OBJECTS had absolutely no intention of going over classes and objects, but lucky for you, my cat just won’t stop purring and for love of God, I cannot fall asleep. So we will quickly rush through the basics. Since the book title claims to be somehow related to pokemons, let’s start with that. Now, what are the things that describe a pokemon? Amongst many, some are - nick name, type, HP, CP, height, weight, etc. Don't take my word for it - consult Pokemon Go.

I

Fig 1.1 Great. Now let’s note down what a pokemon can do. It can go in the Pokeball, come out of the Pokeball and attack. Yep that’s it for now. Equipped with all this information, we get an overview of a pokemon.

2

Fig 1.2 Ladies and gentlemen, a java code representation of the above information is known as a Class. In desperate attempt to make my cat quiet down, we will dedicate this chapter to the Cat God Bastet, by using pokemon Persian in our first example. All Hail Bastet! public class Persian{ String nickName, type; int HP,CP; float height,weight; public void comeBack(){ // come back in the pokeball } pubic void iChooseYou(){ 3

// We know what that means } public void captivate(){ // Its an attack move. you better duck this one }

Basically, a class can be defined as a template that describes state and behavior of an object of this class. What it means is, we can create an Object bastet from the above classPersian bastet =new Persian();

And set the following values for the object: bastet.nickName="Her Highness"; bastet.type="Goddess"; bastet.HP=40;

And so on. We can call the methods likebastet.comeBack(); bastet.iChooseYou(); bastet.captivate();

Objects, like bastet, have a state that is different from other objects of the same class. For example, if we create another object of Persian classPersian thunderCat=new Persian();

And set attributes of thunderCat (completely arbitrary values of my own choice): thunderCat.nickName="Thunder"; thunderCat.type="Normal"; thunderCat.HP= 20;

And so on. 4

Similar to bastet object, we can call the methods on thunderCat object too. thunderCat.comeBack(); thunderCat.iChooseYou(); thunderCat.captivate ();

The data contained by both thunderCat and bastet is different, even when they are objects of the same class. So basically, a class defines the attributes that an object can have and actions it can perform, but the actual value of those attributes are set by the object and are restricted to that object only. This allows multiple objects of the same class to be created containing different values.

Fig 1.3 And I bet you already knew all that. Anyway, all I really wanted was to show off my pokemons. Next up is Access Modifiers. Access Modifiers are a bunch of keywords that can be used to restrict the access to classes, data members (Instance variable) and member functions (methods). Each access modifier

5

allows an instance variable and a methods to be available in a certain scope, as shown below -

Fig 1.4 Can you guess what will be accessible in which scope in the following code? public class Persian { public String nickName; String type; private int CP; protected int HP; public void setCP (int cp){ } void setHP (int hp){ } private int getCP ( ){ } protected int getHP (){ } }

I know it makes no sense to use the modifiers this way for some variables and methods, but the point here is to understand the scope. Also, we will be dealing with protected modifier a lot while studying inheritance.

6

ENCAPSULATION

E

ncapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as single unit. Basically, it means we have to design our class in such a way that the only way any other class can access our data members is using methods. And why exactly your boss makes you do this extra and tedious work? Let’s take a look. We have two pokemons - Electabuzz (Electric) and Crabby (Water). And these pokemons are in a very intense battle at the moment. For the sake of simplicity, let’s only consider their HP. public class Electabuzz { int HP; } public class Crabby { int HP; }

Being a great pokemon trainer that you are, you wrote the classes for all 151 pokemons by yourself (Kudos). And the one who wrote the code for battle simulation is none other than your friend Bob. Now Bob has a bone to pick with you since you stole his lunch money. So he writes his battle simulation method code as public void battleSimulation(Electabuzz ebizz, Crabby crybaby) { ebizz.HP = -25; crybaby.HP = 182; // rest of the apocalyptic code }

Oops! Can you see the problem here? HP should range from 0 to 100, but nothing is stopping Bob from messing up our code by setting invalid values! So how do we make sure that other programmers who apparently couldn't 7

care less of your existence, don't mess up the code? Encapsulation to rescue! First, let’s make data member private. This will ensure that no one can directly assign value to it. Now, we want others to be able to get the value of data member, so we write a get function and return the value. Finally, we want to allow others to set only valid values to our data members, so we write a set function and validate the input before setting the value. And make our getters and setters public. Sounds fun right? Let’s try it. public class Electabuzz { private int HP; public int getHP(){ return HP; } public void getHP(int h){ if(h>=0 && h