Showing posts with label abstract. Show all posts
Showing posts with label abstract. Show all posts

Tuesday, April 5, 2016

Java OOP - Abstraction


Here we go, Abstraction in Java. Probably the hardest concept to understand when you start with OOP. I have to admit it took me a while to really figure out how this concept works and how useful can be.

Abstraction is the process of hiding the implementation details and showing only functionality to the user. In Abstraction we deal with ideas rather than events. Still confused? I know your pain =)

Abstraction in Java is achieved by using interface and abstract classes in Java. In this case, interface or abstract class is "something" that is not complete, something not concrete. So if we want to use interface or abstract class, we are going to need to extend and implement an abstract method with concrete behavior. Got it? not yet? for real? ...no problem, I'll keep explaining..

Imagine you have to define a class "table" but, you still don't know what kind of table it would be. It can be a night table, dinner table, 6 legged table, round table, etc... So, what do you do?, you define an abstract class table, why? because you still don't know what you are going to need later; you have the idea but nothing concrete yet. Just define something abstract.

Another example can be declaring an abstract class Vehicle (which is an abstract idea), then we can have "car", "truck" or "boat" class which can extend Vehicle...

Here is an example of the code:

abstract class Vehicle
{
   public abstract void engine();  
}
public class Car extends Vehicle {
    
    public void engine()
    {
        System.out.println("Car engine");
        //car engine implementation
    }
    
    public static void main(String[] args)
    {
        Vehicle v = new Car();
        v.engine();
        
    }
}


Output
Car engine


Things to remember about abstract class:

  • Can not be instantiated, that's why can not be used directly
  • Abstract classes may or may not contain abstract methods
  • But if a class have at least one abstract method, then the class must be declared abstract
  • If any class contains abstract methods then it must implement all the abstract method of the abstract class







Monday, April 4, 2016

Java OOP - Polymorphism


When I was a kid, I used to watch "Mighty Morphin Power Ranger" on TV, best TV show ever!!! I always wanted to be the Red Ranger!! (but please don't tell my secret lol). Well the point here is that this group of teenager had the ability to "morph" into super-powered warrior. In Java we have something similar and it is called "Polymorphism ".

Polymorphism is in programming, the ability OR capability of a method to behave and do different stuff based on the object that is acting upon.

In Java, Polymorphism has two types:

  • Method Overloading - Compile time polymorphism (static binding) &
  • Method Overriding - Runtime polymorphism (dynamic binding) 

Method Overloading: there are several methods present in a class having the same but different types/order/number of parameters. In this case, Java knows which method needs to invoke by checking the method signatures. 

class DisplayOverloading
{
    public void disp(char c)
    {
         System.out.println(c);
    }
    public void disp(char c, int num)  
    {
         System.out.println(c + " "+num);
    }
}

class Sample
{
   public static void main(String args[])
   {
       DisplayOverloading obj = new DisplayOverloading();
       obj.disp('a');
       obj.disp('a',10);
   }
}

Output:

a
a 10


Method Overriding: If subclass (child class) has the SAME method as declared in the parent class, it is know as method overriding. That is to say, if child class provides the specific implementation of the method that has been provided by one of its parent class, well, this is know as method overriding.

Rules for method overriding:
  • must be IS-A relationship (inheritance)
  • method MUST have same name as in the parent class
  • method MUST have same parameter as in the parent class
  • the access level cannot be more restrictive than the overridden method's access level
  • method declared final cannot be overridden
  • constructors cannot be overridden

class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

class Dog extends Animal{

   public void move(){
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object

      a.move();// runs the method in Animal class

      b.move();//Runs the method in Dog class
   }
}

Output:

Animals can move
Dogs can walk and run











Saturday, April 2, 2016

Java OOP - Encapsulation


Encapsulation is the process of wrapping code and data together into a single unit. "But, hey Rolo how do we do this?"

To achieve encapsulation in your beautiful Java code:

  • Declare the variables of a class private
  • Provide public setter and getter methods to modify and view the variables values.
So the code can go as follow:


/* File name : EncapTest.java */
public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}


In order to avoid any other class to modify our encapsulated class, variables are declared as private and to get access, should be through its public getters and setters.

This is how we access:

/* File name : RunEncap.java */
public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
    }
}

Benefits?

  • Easy to model real-world entities
  • Easy to maintain and understand
  • Control how we access data and how is modified
  • Reusability
  • Flexibility
  • Secure

This short video will help to clarify this concept. Enjoy!







Thursday, March 31, 2016

Java OOP - Inheritance


Inheritance is one of Java OOP concepts. Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviors from the base class.

That is to say, the idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. So the key word here is "reuse code", doesn't sound like a good idea?

Imagine you are sitting at work and get a call your rich uncle died leaving you 1 Billion dollars. What is the first thing you do? Probably SPEND THE MONEY!! HOORAY!!!!...well, with Inheritance, is something similar, but in this case your uncle didn't die but is letting you use his money (methods and fields)

Definitely Inheritance is super useful from a developer perspective, think about it:
  • Reusability -- facility to use public methods of base class without rewriting the same 
  • Extensibility -- extending the base class logic as per business logic of the derived class 
  • Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class 
  • Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class. 
Here is an example, so we can understand better the idea of Inheritance when coding:

class Parent
{
    public void p1()
    {
        System.out.println("Parent method");
    }
}
public class Child extends Parent {
    public void c1()
    {
        System.out.println("Child method");
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.c1();   //method of Child class
        cobj.p1();   //method of Parent class 
    }
}

Output

Child method
Parent method

Wednesday, March 30, 2016

Java Object Oriented Programming (OOP)



Java is so popular nowadays thanks to many features that help developers code faster and efficiently.
One of those important features is : Object Oriented Programming or OOP

But What does it mean? Basically, in Java, everything is an Object. Java can be easily extended since it it based on the Object model. Something like picturing everything as it happens in real world.

For example:

A car is assembled from parts and components, such as chassis, doors, engine, wheels, brake and transmission. The components are reusable, e.g., a wheel can be used in many cars (of the same specifications).

Hardware, such as computers and cars, are assembled from parts, which are reusable components.

How about software? Can you "assemble" a software application by picking a routine here, a routine there, and expect the program to run? The answer is obviously no! Unlike hardware, it is very difficult to "assemble" an application from software components. Since the advent of computer 70 years ago, we have written tons and tons of programs. However, for each new application, we have to re-invent the wheels and write the program from scratch.

As a solution for all this "assemble" and sharing issues. we have Java OOP features. yes! Java saving our life, one more time!!!!

Some of Java OOP concepts are:
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction



oops concept in java




But,"hold on, Rolo, are you saying that we need to change our reliable way to code and leave our comfort and start coding in OO way?"...No! We live in a free country, you don't have to,.lol...However, there are some huge advantages about coding in Java and using its OOP features.....

Benefits of OOP:
  • OOP provides a clear modular structure for programs. 
  • It is good for defining abstract data types. 
  • Implementation details are hidden from other modules and other modules has a clearly defined interface. 
  • It is easy to maintain and modify existing code as new objects can be created with small differences to existing ones. 
  • It implements real life scenario. 
  • More reliable software development is possible. 
  • Much suitable for large projects.

Well, hope you got a good overview about what OOP is. I'll post about every OO concept later....