Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Sunday, August 13, 2017

Inheritance In JAVA: Example

img: Inheritance In JAVA: Example
This is the second last section of the topic Inheritance In OOP where we will study some code snippets. This study will clarify the idea of how to achieve inheritance in JAVA and how it actually works. Without wasting any time and giving length to the post for no reason, let’s start rolling.
Prerequisites: To understand these snippets you should already know what inheritance is. If you don’t, don’t worry. I have a blog post, go here.
Overview: I have written a program named Example which depicts real life inheritance properties like a relationship between child and parent, child access to parent properties etc. The program consists of 4 very simple java classes which are extremely easy to understand. However, if you face any issue ping me in comments. I am always there for you. ExampleBobJohn, and Stephen. The bold faced letters are not names of some persons, in fact, these are names of classes which we are going to study here.
In Java, to establish a child parent relation between two classes, the keyword extends is used at the class declaration time. The child class name is written at the left of the keyword and the parent class name is written on the right side. Syntax:
Child_Class_Name extends Parent_Class_Name
Let’s cast a glance over the access modifiers.
Public: members specified with the public keyword are accessible anywhere in the program using the class object.
Protected: Members modified by protected keyword are accessible within its own class and the child classes without using any object of the parent class.
Privateprivate members are available within the scope of only its own class.
public class Stephen {
protected int money = 5000;

This is the simplest and easiest class I think I have ever seen. As you can see, it only has a single integer data member named money which is initiated to 5000. This class does not extend any class it means that it does not have any parent class. In our story context, Stephen is the grandfather of Bob and have $5000 in his bank account. The variable money is qualified by the keyword protected which means that this variable is accessible in this class and its child classes only. It (variable money) is inaccessible by the object (Object of Stephen Class). Simple.
public class Bob extends Stephen{
protected String eyeColor = "green";
protected String car = "Bob's BMW";

private String mailbox = "Bob's Mailbox";
public void drive() {
System.out.println("Bob is driving: " + car);
public void eyeColor() {
System.out.println("Bob's EyeColor: " + eyeColor);
public void money() {
System.out.println("Bob says: my dad have $" + money);

Bob class extends Stephen class (Bob is a child of Stephen). It has two protected String variables, eyeColor and car and one private String variable, mailbox. What does it show? It shows that the child classes can have or use the eyeColor and car properties while they can't use the mailbox variable. In real life, a child can inherit eye color from his/her parent and can also use their parent’s car but they can’t read their parent’s mailbox unless they are allowed to. While writing this example, I tried to be as real as I could because I think it makes it easier to understand. There are three simple public functions which are accessible through the class object. These functions are self-explanatory.
public class John extends Bob{
public void eyeColor() {
System.out.println("John's eyecolor: " + eyeColor); // note the eyeColor is from 'Bob' Class
public void drive() {
System.out.println("John is driving: " + car); // car is also from Bob class
public void money() {
System.out.println("John says: My grandpa have $" + money); // money is from Stephen class

Class John has nothing more than three functions which simply prints some string with some variables (eyeColor, car, money) from its parent classes. You can see that John is a child of Bob and can access private and public members of Bob class. However, it is using money variable from Stephen class which it does not extends. What the heck is this? Is this correct? Well, yeah! It is correct. The thing is John extends Bob and Bob extends Stephen class so John is also a child of Stephen. Kind of grandchild. This is called multi-level inheritance.
public class Example {
public static void main(String[] args) {
Bob bob = new Bob();
John john = new John();;

Bob is driving: Bob's BMW
Bob's EyeColor: green
Bob says: my dad have $5000
John is driving: Bob's BMW
John's eyecolor: green
John says: My grandpa have $5000

This is the final main class which includes the main function. It simply creates objects of Bob and John classes and calls some of their public functions. Easy. Look at the output and figure out how does it works. It is your home task. If you find yourself in trouble, contact me via comments below.
In coming section, we will discuss why did we study inheritance? And where to use it.  Subscribe using the subscribe button up there in the toolbar and we will notify you when the post is ready. If you have any questions or suggestions, please leave in the comments below and also mark one of the options in the survey popup. 
Stay tuned.

Saturday, June 10, 2017

Inheritance in OOP: Introduction

inheritance in oop-image

In the previous section, we talked about what Object-Oriented Programming is and what are its key concepts or features. We defined them in a very brief and formal way. As I promised that we will discuss each of those in details, here it is. I will try to be as natural as possible.
Inheritance is that feature of Object-Oriented programming which allows developers to borrow code from a prototype (class) and extend it, by adding more properties to it and behaviors to manipulate those properties. It reduces the size of the code with a big margin by creating is-a relationships between objects. This line might sound confusing but don’t worry. You will see in the coming section that how it reduces size of the code. The more common properties and behaviors a program have, the more usable inheritance will be. It allows you (the developer) to implement the real world parent-child hierarchy in a computer in a robust way. Here, I will tell you all I know about inheritance, how to implement it in Java and then where to use it.
Above, I said that inheritance allows developers to implement the parent-child hierarchy in computers like the real world. Inheritance is actually based on the parent-child concept. It has the terms ‘parent’ and ‘child’, which we will define each in the context of OOP but first let me ask you a question. Who is a parent and who is a child, in the real world?  I am sure you will have an answer but if you don’t have, I am happy then that my posts are being read far from the earth. Alright, let’s take our topic seriously.
A child (human) inherits traits from their biological parents like their physical appearance. Children also have access to the property of their parents and have the right to use it unless the property is private to their parents. For example, let’s create a scenario, an inheritance story. John is (a) son of Bob. He resembles his father in many ways because he is his son. Gregor Mendel has explained this through his work on pea plants. Anyhow, He (John) lives with his dad and often drives his car, use his shoe polish, towel etc. But John does not have access to his dad’s private mailbox or Facebook account or anything else which is private to his dad. John also goes to school and gets assignments from his teacher. His dad loves him and helps him often times to complete the assignments but he does not take him with himself to the parties at bar cuz those are private (not for kids sort of party) and John is only 13.
Note the boldface is-a relationship and the things John have access to or what his father does and does not for him. You might have noticed that John can use or know about only the non-private things that his dad own or does. Why? Because they have a relationship between which have its own restrictions. Nobody else can use those property (i.e. those are protected). Now, let’s see these terminologies or concepts or whatever you want to call it, in Object-Oriented Programming.
If you are here, it means that you know what a class is and what an object is. In case you don’t, go here.
In inheritance, classes have is-a relation. The class, which inherits from other class(es) is called child class aka subclass, derived class or extended class and the class which the child inherits from is called parent class or super class or base class. We will use child-parent notation throughout this blog. Like the real world, a class can have many child classes and a child class can have many parent classes. You will see a single example for each case in the next section. The parent class can have private, protected and public members and so can have the child class. The child or derived class have access only to non-private (protected and public) members of its parent class(es). Different languages support different types of inheritance. For example, Java supports single and multi-level inheritance while C++ supports single, multiple and multi-level inheritance. Each language has its own syntax and keywords but the basic concepts are the same. You will need to master only one and then you will be able to go with anyone with a very little work.

Types of Inheritance:

inheritance types-infographic
You might be familiar with the words single, multiple and multi-level inheritance. If you are not, no worries. These are different types of inheritance which you are going to learn in this section. Many authors/programmers include more other types such as hierarchical inheritance, multi-path inheritance and hybrid inheritance in their introductory words to the types but I am not including any other than the basic three types here. In my opinion, the other types are formed by combining the basic types (single, multiple and multi-level). Learn the basics well, it will be easy to learn the rest.
Do you remember John, the main character of our inheritance story? Let’s add more people to his family.
John have a caring mom, Sarah and a loving grandpa, Stephen. We do not need to talk about what they can do or what they have for now. To depict my point clearly, I am including an infographic.
Notice that:

  • The child class in Single Inheritance has a single parent.
  • The child class in Multiple Inheritance has more than one parents (at the same level).
  • The child class in Multi-level Inheritance has a parent and the parent class itself inherits from another parent class. 

Bullets, above are not standards. Variation are possible such as in single inheritance a parent class can have many child classes and a child class can have multiple parent classes at the same level in multi-level inheritance. I hope it makes sense to you.
Alright, we are done for today. You are doing great. Keep learning, sky is the limit. There are great content out there which discuss inheritance further in details. I will encourage you to go for it and study every detail until you feel comfortable with it while coding. You can find some helpful stuff here.
Alright, we are done for today. You are doing great. Keep learning, the sky is the limit.
Next is a How To tutorial where we will talk about how to achieve inheritance in Java, its types and what keywords to use, followed by a very important section where we will discuss where to use which type of inheritance in real projects. Subscribe using the subscribe button up in the toolbar and we will notify you when the tea is ready. If you have any questions or suggestions, please leave in the comments below and also mark one of the options in the survey popup.
Happy coding.

Tuesday, June 06, 2017

What is Object-Oriented Programming? The concept of Class and Objects

what is oop-image
Object-Oriented Programming is a powerful way to address the task of programming. Programming methodologies have improved dramatically since the invention of the computer, primarily to support the growing complexity of programs.
For example, when computers were first invented, programming was done by toggling in the binary machine instructions using the computer's front panel. As long as programs were just a several hundred instructions long, this way worked. As programs grew, assembly language was invented so that a programmer could deal with bigger, more complex programs, using symbolic representations of the machine instructions. As programs continued to grow, high-level languages were introduced that gave the programmer more tools with which to handle complexity.
The 1960s gave birth to structured programming. This is the approach supported by languages such as C and Pascal. The use of structured languages made it possible to write somewhat complex programs fairly easily. Structured languages are characterized by their support for stand-alone subroutines, local variables, rich control constructs, and their lack of dependence upon the GOTO. Although structured languages are a powerful tool, even they reach their limit when a project becomes excessively large. Consider this: At each milestone in the development of programming, techniques and tools were created to allow the programmer to deal with increasingly greater complexity. Each step of the way, the new approach took the best elements of the previous methods and moved forward.
Earlier to the invention of Object-Oriented Programming, many projects were touching the point where the structured approach no longer worked. Object-oriented methods were created to help programmers overcome these limitations. We can say that Object-Oriented programming is inherited from structured programming. It took the best traits/ideas of structured programming and merged them with several new concepts. The result was a different way of organizing a program. In the most general sense, a program can be organized in one  of the two ways:

  1. around its code 
  2. around its data 

Using only structured programming techniques, programs are typically organized around code. This approach can be thought of as "code acting on data." Let's look at an example, a program, written in C (a structured programming language) is defined by its functions, any of which can manipulate data of any type used by the program. Object-oriented programs work the other way around. They are  organized around data, with the key principle being "data managing access to code." In an object-oriented language, you define the data and the routines that are permitted access that data. Thus, a data type defines exactly the ways in which that data can be manipulated. To support object-oriented programming, all OOP languages have three features in common: encapsulation, polymorphism, and inheritance. Let's explore each.

  • Encapsulation

Encapsulation is the mechanism that combines the data and the functions which manipulate that data, and keeps both safe from tampering and misuse. In an object-oriented language, functions and data may be bound together in such a way that a self-contained black box is created. We can only give input to and receive output from the black-box without knowing what is going inside the box. When functions and data are joined together in this manner, an object is formed. In other words, an object is the device that supports encapsulation. 
Within an object, functions, data or both may be private to that object or public to whole program. Private data of an object is only known to functions of that object and private functions are only accessible within the object. Public members (functions and data) are visible to outside of its objects.

  • Polymorphism

Object-oriented programming languages support polymorphism, which is described by the slogan "one interface, multiple methods." In simple words, polymorphism is the property that allows one interface to control access to a general class of actions
For example, you might have a program that specifies three distinct types of stacks. One stack stores integers, one character and the last floating-point values. You can declare functions with the same names, push() and pop() for all three stacks because polymorphism allows you to. You will create three specific variants of these functions, one for each type of stack, but names of the functions will be the same. The compiler will automatically select the appropriate function based on the data being stored.
Polymorphism helps in reducing the complexity of the program by allowing the same interface to be used to access a general set of procedures. It is the compiler's job to select the specific function as it applies to each state. This selection process is automatic and you, the programmer, do not need to participate. You need only to remember and to utilize the general interface.

  • Inheritance

Inheritance is the process by which one object of a class can acquire the resources/properties of another object of another class. This is important because it promotes the idea of classification and largest data is made manageable by hierarchical classifications.
You can take biological classification as an example. For example is Human part of mammalia class, which in tern is part of subphylum vertebrata, which is under the phylum chordata, and so on. Animals in each class share some or more common traits. Without the use of classifications, each object would have to define explicitly all of its characteristics. However, through the use of classifications it an object defined only those properties which make is unique in its gener or class. It is inheritance which makes it possible to for an object to be a specific instance of a general class. As you will see in your programming journey, inheritance is an important feature of object-oriented programming.

Wednesday, May 31, 2017

How To Improve Logic Building Skills In Programming?

how to Improve logic building skills in programing-img
[DISCLAIMER]: Everything in this article is my own opinion and these are not standards. Feel free to criticize.
I frequently see beginners asking questions in forums like 'how can I improve my logic building skills' or 'how to think logically or something like 'how to think like a programmer' and blah, blah. If you have similar questions in your mind then follow along. I know, I am not the best but I will share my experience and I hope you will find it helpful.

Sunday, May 14, 2017

Programming Can Cause Health Problems: Read Some Health Tips Here

"He who has health has hope, and he who has hope has everything."
I am writing this article with no intentions of making you feel guilty about your lifestyle. I just want to share a few tips which I use myself which helps me to stay healthy. One should have good cognitive abilities to become a good programmer, in my opinion, but poor physical health can lead to an increased risk of developing mental health problems. A surprising number of developers suffer from health issues due to their sedentary lifestyle.
We, I mean developers ;) ignore little things which can bring big changes. We forget that it's the little things that matter most.
In my case, programming has given me fun and money but some health problems too. I don't want and I am sure nobody wants to take medicine which tastes like shit or something else like this. Last year I was reading I decided to change my lifestyle. Last year I found the book, The Healthy Programmer, in the library. I read it and I find it very helpful. Here, I will share some tips which I follow.

  • Exercise on regular basis:

Everyone knows that exercise is key to good health. You can find a lot of research which shows how exercise affects health. 
There is no need to go to a gym and lift heavy weights but doing some form of exercise pays in the long run. exercising regularly keeps your body fit and improves your physical and mental health. If you walk to your workplace or go up and down on stairs frequently, you are almost done. You can also do some exercise even while you are on your desk. You don't need to leave the desk and go to a walking track or a park. It will keep you fresh and focused.

  • Don't stay up all night:

Programming is a back-breaking and taxing job. It sometimes needs you to stay awake and on the ball all the night. But making it into a habit can screw up your health. A study showcased by the APSS (Associated Professional Sleep Society) suggests that lack of sleep adversely impacts one's retention capacity and the ability to solve problems. Sleep deprivation can impair your brain activity and can cause cognitive dysfunction. Sleep makes you feel better, but its importance goes way beyond just boosting your mood or banishing under-eye circles. Adequate sleep is a key part of a healthy lifestyle and can benefit your heart, weight, mind, and more. But sleep all day or stay up all night is not the goal. I personally don't like the thought of 8 hours a day of sleep. The goal is to think big and develop bigger. But once the focus is lost, then it's time to go to sleep. 

  • Take proper food:
Programmers drive themselves to unhealthy conditions just in the interest of their goals. They eat at restaurants very often or grab candy in the office  because of the lake of time. They don't have time for lunch. All these are nothing but bad habits. Take a closer look at your dietary habits and use the latest science to create an eating plan that is personalized for you.  Creating a balanced diet is very simple. WHO, US Department of Health and Human Services and US Department of Agriculture recommend that a healthy daily diet consists of the following components: 30% grains and starches 30% fruits and vegetables 16% dairy 16% lean protein (meat, fish, eggs etc) 8% fatty and sugary foods There is no perfect diet but it is a good idea to rotate through the categories. Eat but with care.

  • Move somewhat

It is important to be conscious of your posture. The number of people suffering from injuries due to bad posture is increasing. Dr. Hedges recommends setting for no longer than 20 minutes. The alternative is standing desk. In the beginning, it seems difficult for our body to accept the new setup. Therefore take the incremental approach and gradually increase the time you spend on standing desk. But standing for longer than 20 minutes is also not recommended. Also, follow 20-20-20 rule. After 20 minutes of screen time, look for 20 seconds at objects which are 20 feet away. This will relax your eyes and avoid eye redness.

The point is, Change if it hurts and walk when you can, just keep your body moving.

  • Make a good posture
Bad posture is something that many developers ignore unless they feel the pain. Wrist pain, back pain, neck pain, joints pain etc might be caused by the way you sit, stand or type on the keyboard. The distance between the screen
and your eyes and the angle also matters. 
Programmers and pianists have a lot in common. They spend hours a day sitting in a chair in front of the keyboard. Only a few of them might know how to position their bodies for this task. 
The correct posture depends on the individual. The position which works for me, might not work for you. There are no specific ways you can follow, but here are some very common rules that work for everyone:
* Adjust your chair height so that your hips are level with your knees and you do not slide backward or forward in the seat.
* Adjust your desk height so that your elbows are level with your wrists. 
* As you sit in your chair, ensure that you are placing even amounts of weight on your front, back, and side supports.
* One of the important aspects of posture is keeping your feet on the ground. If you are good with your posture but your feet are above the ground, then you may want to use a small footrest to prop up your feet.

Sunday, March 19, 2017

10 Tips to improve your coding skills

10 tips to improve coding skills-img
You want to be a programmer and you are struggling for it. Don't worry, it is the way how it works but how your struggle returns to you really depends upon the way you learn, the way you practice and the way you think. You want to be a programmer who makes the logic very quickly and write almost half of the code in mind while studying the problem.