Sunday, October 28, 2018

OOP concepts

Hello friends! In here I am going to describe background to Object Oriented concepts and them.

Do you know about these things?

Simula - the first object - oriented programming language
smalltalk - the first pure object - oriented language
other - ex: Java, C#, PHP, Phython, C++

The main objective of oop is to implement real  world entities.Before that lets see what is a class  and an object .

What is an object in oop ?
An Object is a real world entities with state and behaviors . ex:pen,chair,car
It is an instance of a class. An object has an address and take some memory in space.

ex: object - baby
      state/data/attributes             - name ,age ,weight,date of birth
      behaviors/methods              -  laughs,drinks,sleeps,cries

In here state are descriptive characteristics. Behaviors tell us what object can do.

What is a class in oop?
A class is a collection of objects.It is logical entity. On the one hand it is a category or group of things that have similar attributes and common behaviors.On the other hand it is a blueprint from which individual objects are created.


Then we are going to talk about concepts which are associated with oop.

1.Inheritance("is-a" relationship)
non-private members of the super class inherit to the sub class.

It is the process by which one class acquire  the properties and behaviors of another class(parent class).It provides code re usability.



Lets see  examples for inheritance.

public class Dog{
public static void main (String[]args){

}
}

public class Puppy extends Dog{
}

All the states and behaviors can have puppy.Also  the states and behaviors which are  specific to puppy can have. The reality is "puppy is a dog". In here you can see "is-a relationship " between puppy and dog.

class Parent{
int height =120;
void sing(){
System.out.println("classical");
}

}
class Child extends Parent{

}

class Test{
public static void main(String[]args){
Parent p = new Parent (); // creating parent type object
p.sing();
System.out.println(p.height);
Child c =new Child(); // creating child type object
c.sing();
System.out.println(c.height);
}
}

output
classical
120
classical
120

According to above example Parent can sing ("sing()"method ) and height is 120.They are not private variables or methods.When Child extends to the Parent ,super   class (attributes and behaviors of super class  ) inherits to the sub class.

ex:
class Bird {
public String reproduction = "egg";
public String outerCovering = "feather";

public void flyUp() {
System.out.println("Flying up...");
}
public void flyDown() {
System.out.println("Flying down...");
}
}

class Eagle extends Bird {
public String name = "eagle";
public int lifespan = 15;
}


class TestEagle {
public static void main(String[] args) {
Eagle myEagle = new Eagle();

System.out.println("Name: " + myEagle.name);
                System.out.println("Reproduction: " + myEagle.reproduction);
System.out.println("Outer covering: " + myEagle.outerCovering);
System.out.println("Lifespan: " + myEagle.lifespan);
myEagle.flyUp();
myEagle.flyDown();
}
}

output
Reproduction:  egg
Outer covering: feather
Lifespan: 15
Flying up...
Flying down...

2.Encapsulation (hide the implementation)
The wrapping up data and methods into a single unit(class) is known as encapsulation.
Ex: capsule (it is wrapped with different medicine)
 Usage

Data hide(security purposes)

For avoid entering wrong data (ex: In a system you have to enter your age in one field, If you give  negative , zero or sometimes value is more than 100 in there , If value  map with age but it can not practically happen. )


class Student{

private int id;
private String name;
private  int age;

public void setId(int id){
this.id =id;}

public int getId(){
return id;
}

public void setName(String name){
this.name =name;}

public String getName(){
return name;
}

public void setAge(int age){
this.age =age;}

public int getAge(){
return age;

}}


class Test{
 public static void main(String[] args) {
        Student s =new Student();
        s.setName("uresha");
        s.setAge(22);
        s.setId(7);
        System.out.println(s.getName());
        System.out.println(s.getId());
        System.out.println(s.getAge());
    }

}

output
uresha
7
22

3.Polymorphism
when one task is performed by different ways we can use this. we use following two things two achieve this.


  • method overriding (dynamic polymorphism)
  • method overloading (static polymorphism)
Method overloading (static polymorphism)
  • class has multiple methods in same name with different parameters
  • two ways to overload a method (by changing data type ,by changing no. of arguments)
  • advantage - increases the readability of the program


class Bird {
public void fly() { //no parameter
System.out.println("The bird is flying.");
}
public void fly(int height) { // int parameter
System.out.println("The bird is flying " + height + " feet high.");
}
public void fly(String name, int height) { //string and int parameters
System.out.println("The " + name + " is flying " + height + " feet high.");
}
}

class TestBird {
public static void main(String[] args) {
Bird myBird = new Bird();

myBird.fly(); // call no parameter
myBird.fly(10000); // call int parameter
myBird.fly("eagle", 10000); // call string and int parameters
}
}


output
The bird is flying.
The bird is flying 10000 feet high.
The eagle is flying 10000 feet high.

Method overriding (dynamic polymorphism)


  •  can override the methods of the parent class from its child class.            

class Animal {
public void eat() {
System.out.println("This animal eats insects.");
}
}

class Bird extends Animal {

public void eat() {
System.out.println("This bird eats seeds.");
}

}

class TestBird {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.eat();

Bird myBird = new Bird();
myBird.eat();
}
}

output
This animal eats insects.
This bird eats seeds.

4.Abstraction

Hide complexity from the users and show them only the relevant information .
ex: if you want to drive a car , you do not need to know about its internal working process.

We can hide internal implementation details using abstract classes (can achieve partial abstraction )or interfaces(total abstraction).

abstract method-  has only method signature
concrete method - has method body

abstract class Animal {
// abstract methods
abstract void move();
abstract void eat();

// concrete method
void label() {
System.out.println("Animal's data:");
}
}



class Bird extends Animal {

void move() {
System.out.println("Moves by flying.");
     }
void eat() {
System.out.println("Eats birdfood.");
}
}

class Fish extends Animal {
void move() {
System.out.println("Moves by swimming.");
     }
void eat() {
System.out.println("Eats seafood.");
}
}

class TestBird {
public static void main(String[] args) {
Animal myBird = new Bird();

myBird.label();
myBird.move();
myBird.eat();
}
}

class TestFish {
public static void main(String[] args) {
Animal myFish = new Fish();
                myFish.label();
myFish.move();
myFish.eat();
}
}


 output of TestBird
Animal's data:
Moves by flying.
Eats birdfood.

output of TestFish
Animal's data:
Moves by swimming.
Eats seafood.

**Interfaces

Java interfaces  use for implement multiple inheritance.A class can implement any no. of interfaces.
Classes can access an interface using implements keyword.

interface Animal {
public void eat(); // abstract method
public void sound();  // abstract method
}

interface Bird {
int numberOfLegs = 2;  // static field
String outerCovering = "feather";   // static field

public void fly();  // abstract method
}

class Eagle implements Animal, Bird {
//it defines own functionality for 3 abstract methods eat(),sound() and fly()
public void eat() {
System.out.println("Eats reptiles and amphibians.");
}
public void sound() {
System.out.println("Has a high-pitched whistling sound.");
}
public void fly() {
System.out.println("Flies up to 10,000 feet.");
}
}

class TestEagle {
public static void main(String[] args) {
Eagle myEagle = new Eagle();

myEagle.eat();
myEagle.sound();
myEagle.fly();
                                                                                //in here static object does not belong to  specific object but belongs to whole class.So we use Bird interface .
System.out.println("Number of legs: " + Bird.numberOfLegs);
System.out.println("Outer covering: " + Bird.outerCovering);
}
}

output of TestEagle
Eats reptiles and amphibians.
Has a high-pitched whistling sound.
Flies up to 10,000 feet.
Number of legs: 2
Outer covering: feather


Let us try to understand a little about all these, through a simple example.

 Human Beings are living forms, broadly categorized into two types, Male and Female. Right? Its true. Every Human being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are body parts that are common for Male and Female, but then there are some specific body parts, present in a Male which are not present in a Female, and some body parts present in Female but not in Males.

All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs some
common functions, but there are some specifics to both, which is not valid for the other.
For example : A Female can give birth, while a Male cannot, so this is only for the Female.

Class

Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its properties and its functions.
 Like Human Being, having body parts, and performing various actions.

Inheritance

Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat, see etc.
 Male and Female are also classes, but most of the properties and functions are included in HumanBeing, hence they can inherit
everything from class HumanBeing using the concept of Inheritance.

Objects

My name is Abhishek, and I am an instance/object of class Male.When we say, Human Being, Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes.
 We have a physical existence while a class is just a logical definition. We are the objects.

Abstraction

Abstraction means, showcasing only the required things to the outside world while hiding the details.
 Continuing our example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world.
 We can take our skin as the Abstraction factor in our case, hiding the inside mechanism.

Encapsulation

This concept is a little tricky to explain with our example.
Our Legs are binded to help us walk. Our hands, help us hold things.
 This binding of the properties to functions is called Encapsulation.

Polymorphism

Polymorphism is a concept, which allows us to redefine the way something works,
by either changing how it is done or by changing the parts using which it is done. Both the ways have different terms for them.

If we walk using our hands, and not legs, here we will change the parts used to perform something.
 Hence this is called Overloading.

And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else.Then I can walk like I want, this will be called as Overriding.







Thursday, October 18, 2018

Access Modifiers In Java

Hi! friends, In here I am going to describe  access modifiers ,access levels and somewhat about package hierarchy in java.

There are 3 access modifiers in Java.
1.public
2.protected
3.private

Also there are 4 access level in Java.

1.public - with public keyword
2.protected - with protected keyword
3.default - no keyword here
4.private - with private keyword



 According to above image , "public " can use within the class, within the package , outside package by sub class only and outside package.

"private" can only use within the class

"default " can use within class and package.

"public" can use in above all places.

These things can easily understand with variables and methods...

Package Hierarchy

A package can exist inside another package.
According to this case there are 3 packages exist.
  - pack1
  -pack1.pack2
  -pack1.pack2.pack3

If we getting only packages as pack2 and pack3 they are not packages.We should use complete name of them as above.

ex: class A presents in the package pack1
      class B presents in the package pack1.pack2




package pack1;
class A{
public static void main(String[]args){
System.out.println("A");
}
}


package pack1.pack2;
class B{
public static void main(String[]args){
System.out.println("B");
}
}

package pack1.pack2.pack3;
class C{
public static void main(String[]args){
System.out.println("C");
}
}


Wednesday, October 3, 2018

Control Statements

Hi! guys , through this part  I am going to explain control statements which we can see in Java. These  control statements's behaviors are common for any programming language. But for further purposes you should need basic understand about these things.

Lets discuss about them step by step.

Under this topic we can see two kind of control statements.(control structures in java)
1.Selection Structure
2.Repetition  Structure


  • Selection Structure

 Under this one we can see ,

                                        single selection - if
                                        double selection - if else
                                        multiple selection - switch

If statement

 In here , in if statement  a condition is tested, and if the condition meets the test , the relevant code is executed.

public class IfExample {
public static void main(String[]args){
int age =30;
if (age>18){
System.out.println("Age is grater than 18");
}
}
}


If Else statement


In here a different code is executed if the condition fails the test.

public class IfElseExample{
public static void main(String[]args){
int age =12;
if (age>=18){
System.out.println("You can vote");
}else{
System.out.println("You can't vote");
}
}
}

In above examples we declared a variable and initialized it. That means we created a variable called "age" int type  and assign value 18 to it.

 Can't we do this using keyboard input?
Yes.  We can.
 For that you should import  under java.util.package classes  , java.util.Scanner  class .

Let's see how we write if-else statement using Scanner.

import java.util.Scanner;
public class Vote{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter your age : ");
 // you should give keyboard input at here. The cursor will wait for you when you run your program until you enter int value  as your age.
int age = s.nextInt();
// In here we convert our input to int value whether it is String .We can talk about these things further under  Wrapper Class topic
if (age>=18){
System.out.println("You are eligible for voting");
}else{
System.out.println("You are ineligible for voting");
}
}
}

If-Else-If statement

In here a different codes are executed if the condition fails again and again.

import java.util.Scanner;
public class IfElseIfExample{
public static void main(String[]args){
 Scanner s = new Scanner (System.in);
System.out.println("Enter your marks : ");
int marks = s.nextInt();
if ((marks<55 ) {
System.out.println("You have no grade");
}
else if ((marks>= 55) &&  (marks<65) ) {
System.out.println("Your grade is C");
}
else if ((marks>= 65) && (marks<75) ) {
System.out.println("Your grade is B");
}
else if ((marks>= 75) && (marks<=100) ) {
System.out.println("Your grade is A");
}
else ((marks>100 ) {
System.out.println("Invalid input");
}
}
}

Nested If Statement
In here we can see if block within another if block. Also you can use else part here.

import java.util.Scanner;
public class NestedIfExample{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter your age : ");
System.out.println("Enter your weight : ");
 int age = s.nextInt();
int weight = s.nextInt();
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood ");
}else{
System.out.println("Your weight is not enough for donate blood");
}
else {
System.out.println("Your age is not enough  for donate blood");
}
}
}


For multiple selection you can use switch statement.

 In here if the value  of the control expression does not match any of the values then the default case is executed.

Switch  Statement

import java.util.Scanner;
public class SwitchExample{
public static void main(String[]args){

Scanner s = new Scanner(System.in);
     
                  System.out.println("enter value of the day");

                 int day = s.nextInt();

                 switch(day){
                 case 1:         System.out.println("Today is monday");break;
                 case 2:         System.out.println("Today is tuesday");break;
                 case 3:         System.out.println("Today is wednesday");break;
                 case 4:         System.out.println("Today is thursday");break;
                 case 5:         System.out.println("Today is friday");break;
                 case 6:         System.out.println("Today is saturday");break;
                 case 7:         System.out.println("Today is sunday");break;
                 default:          System.out.println("invalid");
                 }
}}



  • Repetition Structure
Sometimes we want to repeat certain  things many times.
ex: Printing a list of names.
      Generating a series of random numbers
Under this topic we can identify loops.Let's see  about them.

For Loop

for(initiate action; boolean expression;action after each iteration)
{Statements to be repeated ; }
 
Inside main method , try to get output of the following for loops.


ex 1 :             for(int i=0;i<5;i++){
                       System.out.println("loop "+i);
                        }


                        for(int i=5;i>0;i--){
                       System.out.println("loop "+i);
                       }


                        for(char ch='a';ch <='z';ch++){
                        System.out.println(ch);
                        }
     
    

                      int array[] ={34,67,78};
                    for(int i=0;i<array.length;i++){
                    System.out.println(array[i]);
                    }

While Loop

This one continually executes a block of statements  while a particular condition is true.

                     
                     int i=2;

                     while(i<7){
                     System.out.println("while loop " + i);
                         i++;
                       }



Do while Loop

 In here the statements within the do block  are always executed at least once.

                       int i=10;

                        do{
                        System.out.println("do while loop " + i);
                        i--;
                         }
                      while(i>0);
    

Break

This one is used to exit from loop.



                         for(int i=10;i>0;i--){
                         System.out.println("loop " +i);
                          if(i==5){
                         break;}
                           }

In above example it will print from loop 10 to loop 5 without others. Because we have put break when i ==5 . So loop will exit from that place.