Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Java Basics - Lecture 5 - What is Inheritance in Java?

The Hacks of The Day














Inheritance in Java

A process in which one class utilizes the property of another class is called Inheritance. The class that's utilizing the property of another class is called a child class, and therefore the other is called parent class.

It facilitates the code reusability so that a class has to write only the unique features and the rest of the common properties(Data Members) and functionalities(Member Functions) can be extended from another class. Child Class: The class that extends the features of another class is known as child class, subclass or derived class. Parent Class:

The class whose properties and functionalities are inherited by another class is known as a parent class, superclass, or Base class. The process of defining a new class based on an existing class that extends its common data members and methods is called inheritance. Inheritance allows us to reuse code, it improves reusability in your java application.

Note: The main advantage of Inheritance is code reusability, the code that is already present in base class need not be rewritten in the child class.

Syntax: To inherit the properties of a class we use extends keyword. Here class B is child class and class A is parent class. Class B is inheriting the properties and methods of Class A.
class B extends A
{  
}  

Inheritance Example: 

In the following example, we have a base class Shape and a subclass Circle. Since class Circle extends the width and height properties and area() method from the base class, we need not declare these properties and methods in the subclass. Here we have width, height, and area() method which are common to all the shapes so we have declared them in the base class, this way the child classes like Circle, Rectangle and Triangle do not need to write this code and can be used directly from the base class.
class Shape {
   int width = 20;
   int height = 30;
   public void area(){
    System.out.println("Shape");
   }
}
class Circle extends Shape{
    double radius = 40;
    public static void main(String args[]){
    Circle obj = new Circle();
    System.out.println(obj.width);
    System.out.println(obj.height);
    System.out.println(obj.radius);
    obj.area();
   }
}
Output:
20
30
40
Shape
So based on the above example we can say that Circle IS-A Shape. In Java, a child class has an IS-A relationship with the parent class. This is inheritance is known as the IS-A relationship between the child and parent class.

Important Note!! 

The derived class can inherit all the data members and member functions that are declared as public or protected. If the data members or member functions of the superclass are declared as private then the derived class cannot use them directly. The private members are only accessible in its own class. To access private members out of class, getter and setter are used.

Types of Inheritance:

There are different types of inheritance in Java:

  1. Single inheritance
  2. Multiple inheritances
  3. Multilevel inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance


Single inheritance: In single inheritance, a derived class is created from one parent class. It refers to a child and parent class relationship where a class extends another class. Syntax:
//Parent Class
class Parent 
{
   //methods and fields  
}
//Child Class
class childClass extends Parent
{  
   //methods and fields  
}
Let's take an example. Suppose we have a parent class "Vehicle" and child class "Car". Child class will acquire the features of the parent class. As shown in the main method we have created an object of the child class, this object will call the methods of both classes (Child & Parent)
class Vehilce {
 public void engine() {
  System.out.println("engine...");
 }
}
class Car extends Vehicle {
 public void start() {
  System.out.println("start...");
 }
}
public class ExecuteClass {
 public static void main(String args[]) {
  Car c = new Car();
  c.engine();
  c.start();
 }
}
Multiple inheritances: In multiple inheritance one class extending more than one class, which means One child class has two parent classes. As per the above diagram, Class C extends Class A and Class B both.

Multilevel inheritance: In multilevel inheritance, one class can inherit from the child class. Hence, the child class becomes the parent class for the new one. As shown in the below diagram Class C is a child of Class B and B is a child class of Class A.

Hierarchical Inheritance: In hierarchical inheritance, more than one classes extend one class. In the below diagram Class B, C, and D inherit the same class A.

Hybrid Inheritance: Hybrid inheritance is a combination of Single and Multiple inheritances in a single program. As per the below example, all the public and protected members of Class A are inherited into Class D, via Class B and Class C.

Note: Java doesn't support hybrid/Multiple inheritances

Constructors and Inheritance: 

When you create an object of a child class, it's constructor is called, it by default invokes the superclass class default constructor. In inheritance, constructors are called in a top-down approach.

A SuperClass constructor is called by using super keyword. The super keyword refers to the superclass, immediately above the calling class in the hierarchy. To access the data members or methods of the parent class super keyword is used.
class ParentClass{
   //Parent class constructor
   ParentClass(){
    System.out.println("Constructor of Parent");
   }
}
class ChildClass extends ParentClass{
   ChildClass(){
    
    System.out.println("Constructor of Child");
   }
   public static void main(String args[]){
    //Creating the object of child class
    new ChildClass();
   }
}
Output:
Constructor of Parent
Constructor of Child

Inheritance and Method Overriding: 

To declare the same method in child class which is already present in the parent class then this is called method overriding. In this case, when we call the method from the child class object, the child class version of the method is called. However, we can call the parent class method using the super keyword as I have shown in the example below:
class ParentClass{
   //Parent class constructor
   ParentClass(){
    System.out.println("Constructor of Parent");
   }
   void disp(){
    System.out.println("Parent Method");
   }
}
class ChildClass extends ParentClass{
   ChildClass(){
    System.out.println("Constructor of Child");
   }
   void disp(){
    System.out.println("Child Method");
        //Calling the disp() method of parent class
    super.disp();
   }
   public static void main(String args[]){
    //Creating the object of child class
    ChildClass obj = new ChildClass();
    obj.disp();
   }
}

Summary: 

Inheritance means to inherit the properties from parent. A child can inherit all properties from the parent. A parent can have multiple children. A child can have only one parent. When the method is present in the parent class as well as in child class with the same name and same parameters – Method Overriding. Preference will be given to the overridden method. The super keyword is used to access parent class features.

Java Basics - Lecture 4 - What is class and object in Java

The Hacks of The Day
Java Class and Object

This lecture will cover basic OOP concepts. What is Class and Object? What is the difference between them?

Lecture 4 Agenda


1) Class
2) Object

Classes and objects are the fundamental parts of OOP. In OOP, we try to map real-world entities into software objects. Although there is a confusion between object and class, in this article, we will try to explain the difference between object and class. First, let's understand what they are.

What is a class?

A class is a blueprint or template for objects. It defines the behavior of objects. It determines how an object will behave and what the object will contain. In other words, a set of instructions to build a specific type of object.

Syntax:

public Class {
 Data Members;
 Member Functions;
}

Class Components:

Access Modifiers: A class can be public or has default access.
Class Name: The class name begins with a Capital letter.
Class Body: The class body is shown by curly braces, { }. It contains data members and member functions.

What is an Object?

An object is an entity with some attributes and behavior. When we look around, we see many examples of real-world objects: dog, desk, television, bicycle, etc. The real-world objects have two characteristics one is called "state" and the other is "behavior".

For example, dogs have state (name, color, breed, age, size) and dogs have behavior (barking, eating, running, sleeping). In terms of Software objects, they also have state and behavior.

Remember: To create an object of a class"new" keyword is used.

Syntax:
ClassName ReferenceVariable = new ClassName();

An object consists of :

State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by methods of an object. It also shares the response of an object with other objects.
Identity: It assigns a unique name to an object and enables one object to interact with other objects.

When an object of a class is created the class is called instantiated. All the instances share the attributes and the behavior of the class, the state will be different for each object. A single class can have more than one instance. As shown in the below image.

What is object and class in Java

Let's take an example of a class Car. Below is the Java code for this class.
//Class Declaration

public class Car {
 // Instance Variables
 int model;
 int wheel;
 String color;
 // Member Function
 public String getInfo() {
  return ("Modal is: " + model + " Wheels are: " + wheel + " Color is: " + color);
 } 
 public static void main(String[] args) {
  Car car = new Car();
  car.model = 2015;
  car.wheel = 4;
  car.color = "while";
  System.out.println(car.getInfo());
 }
}
Output: 

Modal is: 2015 Wheels are: 4 Color is: white

In the above example, we created one reference variable (car) and assigned a new instance of the Car class to this variable. Such an object is also called an instance of the class.

Summary:

A class is a user-defined blueprint or template from which objects are created. It determines how an object will behave and what the object will contain.
A Java object consists of methods and properties to make a certain type of data useful.
A class system allows the program to define a new class (child class) in terms of an existing class (parent class) by using a technique like inheritance, Polymorphism, and overriding.

Java Basics - Lecture 3 - Loops in Java

The Hacks of The Day

Loops in Java














Loops are used to perform a task repeatedly. There are 3 types of loops

  1. while loop
  2. for loop
  3. do-while loop

Suppose if you want to print first 5 digits

You need to write 5 print statements

System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);

Instead of writing repeated code, we use loops

While loop :

A control flow statement which is used to perform the repeated tasks based on a given Boolean condition. In while loop number of iterations is not fixed. Loop will be executed only if the condition is true. It is also called the entry control loop.

Flow Chart Diagram



Disadvantage: It generates an infinite loop if we don't give an incremental part

For Loop:

A control flow statement which is used to perform repeated tasks. But in for loop number of iterations are fixed.

Flow chart Diagram



Parts of for loop (Initialization, Conditional part, Incremental part)

Initialization: In this part, the variable is initialized. It is a starting point of the loop

Condition: In this part condition is checked, it returns a boolean. In the case of the true, the loop body is executed.

Increment/Decrement: Variable is incremented or decremented here for next iteration

Loop termination: When the condition becomes false, then the loop is getting terminated.

For Loop Example




public class ForLoop {
public static void main(String[] args)  {
  for(int j=1;j<=10;j++){
  System.out.println("Values of ==> " + j);
  }
 }
}

Output:
value of j ==> 1
value of j ==> 2
value of j ==> 3
value of j ==> 4
value of j ==> 5
value of j ==> 6
value of j ==> 7
value of j ==> 8
value of j ==> 9
value of j ==> 10
If you want to print 10 digits in reverse order then below code will work fine.

public class ForLoop{
 public static void main(String[] args){
  for(int k=1;k<=10;j--){
  System.out.println("Values of ==> " + k);
    }
  }
}

Post Increment

An operator that is used to increment the value of the variable after the expression is executed in which post-increment is used. The value is first used in an expression and then incremented.
public class PostIncrement{
 public static void main(String[] args){
 int i = 1;
 int j = i++; //post increment

   }
}

Pre Increment

An operator that is used to increment the value of the variable before the expression is executed in which post-increment is used. The value is first incremented in an expression and then used.  
public class PreIncrement{
 public static void main(String[] args){
 int a = 1;
 int b = ++a; //pre-increment
   } 
}

Post Decrement

An operator that is used to decrement the value of the variable before the expression is executed in which post-increment is used. The value is first decremented in an expression and then used.  
public class PostDecrement{
 public static void main(String[] args){
 int i = 2;
 int j = i--; //post decrement
   }
}

Pre Decrement

An operator that is used to decrements the value of the variable before the expression is executed in which post decrement is used. The value is first decremented in an expression and then used.  
public class PreDecrement{
 public static void main(String[] args){
 int a = 2;
 int b = --a; //pre-decrement
 System.out.println("Value of a ==> "+a);
 System.out.println("Value of b ==> "+b); 
  }
}

do-while loop :

The do-While loop is similar to while loop but the difference is that the body of the do-while loop is executed once and then the condition is verified. A control flow statement that executes a piece of code at least once.

Flow Chart Diagram


If the test expression is true, the body of the loop is executed again and the test expression is evaluated.

The first loop body is executed then the condition is checked, this process continues until the condition is false.

This process goes on until the test expression becomes false.

If the test expression is false, the loop ends.


public class DoWhileLoop{
 public static void main(String[] args){
 int counter = 5;
 int factorial = 1;
 do{
    factorial *= counter--;
 }while (counter > 0);
 System.out.println("result " +factorial);
  }
}
Output:
 result ==> 120

Array in Java

Array: Stores similar data type values in an array variable.
  1. A collection of similar data types
  2. The lowest index is always “0”
  3. The highest index is always n-1 (n is the size of the array)
Int array
Integer array stores the integer data type. 
 int arr[] = new int[4];
 arr[0] = 10;
 arr[1] = 20;
 arr[2] = 30;
 arr[3] = 40;
 System.out.println(arr[2]);
 System.out.println(arr[3]);

Output:
value of arr[2] ==> 30
value of arr[3] ==> 40

If you will try to find the arr[4], it will give exception

When you go beyond the limit, an exception will raise “ArrayIndexOutOfBoundsException”

Size of array
The size of the array is determined by using length() method.
System.out.println(arr.length)
Print all the values of the array: use for loop
 for(int i=0; i < arr.length; i++){
 System.out.println(arr[i]);
 }
Double array
Double array stores the double data type. 
double d[] = new double[3];
d[0] = 3;
d[1] = 14.33;
d[2] = 44.89;
Character array
Character array stores the character data type. 
char c[] = new char[3];
c[0] = 'a';
c[1] = '3';
c[2] = '$';
String array
String array stores the string data type. 
String s[] = new String[3];
s[0] = "test";
s[1] = "World";
s[2] = "Hello";
Disadvantages:
  1. The array size is fixed. Therefore it is called a static array
  2. Stores only similar data types
To overcome size problem we use Collections like ArrayList, HashTable
To overcome data type problem we use Object array
Object array(Object is a class) – It is used to store different data types

Object array
 Object obj[] = new Object[6];
 obj[0] = "Tom";
 obj[1] = 25;
 obj[2] = "M";
 obj[3] = 12.33;
 obj[4] = "1/10/1998";
 obj[5] = "London";
Find all elements of Object array
for(int i=0; i<obj.length; i++) {
 System.out.println(obj[i]);
}
Output
value of obj[0] ==> Tom
value of obj[1] ==> 25
value of obj[2] ==> M
value of obj[3] ==> 12.33
value of obj[4] ==> 1/10/1998
value of obj[5] ==> London

2D Array in Java
Collection of data in the form of cells
Represented as a matrix with a number of rows and columns
String x[][] = new String[3][5];
Output:
System.out.println(x.length);
Number of row ==> 3
System.out.println(x[0].length);
Number of columns ==> 5
//1st row

x[0][0] = "A";
x[0][1] = "B";
x[0][2] = "C";
x[0][3] = "D";
x[0][4] = "E";
//2nd row

x[1][0] = "A1";
x[1][1] = "B1";
x[1][2] = "C1";
x[1][3] = "D1";
x[1][4] = "E1";
//3rd row

x[2][0] = "A2";
x[2][1] = "B2";
x[2][2] = "C2";
x[2][3] = "D2";
x[2][4] = "E2";
Output
System.out.println(x[1][2]);
value of x[1][2] ==> C1</
System.out.println(x[2][2]);
value of x[1][2] ==> C2
System.out.println(x[0][4]);
value of x[1][2] ==> E
Print all the values of 2D array
Two for loops are required to get array values
//row = 0, col = 0 to 4
//row = 1, col = 0 to 4
//row = 2, col = 0 to 4

for(int i = 0; i < x.length; i++){
  for(int j = 0; j < x[0].length; j++){
  System.out.println(x[i][j]);
   }
}
Output:

  value of x[0][0] ==> A value of x[0][1] ==> B
  value of x[0][2] ==> C value of x[0][3] ==> D
  value of x[0][4] ==> E

  value of x[1][0] ==> A1 value of x[1][1] ==> B1
  value of x[1][2] ==> C1 value of x[1][3] ==> D1
  value of x[1][4] ==> E1

  value of x[2][0] ==> A2 value of x[2][1] ==> B2
  value of x[2][2] ==> C2 value of x[2][3] ==> D2
  value of x[2][4] ==> E2

Java Basics - Lecture 1 - What is Java

The Hacks of The Day















In this session, we will cover Java basics. To learn selenium it is very important to learn Java. Without Java, you can not learn Selenium. Although many other languages are available that are supported by Selenium Selenium with Java is the best combination. 90% of companies use this combination. If you have manual testing the background then these videos are very helpful for you to learn Java basics, not advanced Java. To learn Selenium only core Java basics are required not advanced Java. We will cover the following topics:

Lecture 1 Agenda:

  1. What is Java
  2. What is Eclipse
  3. Data types in Java
  4. What is System.out.println() and System.out.print()

1) What is Java?

- A computer programming language.
- Open source technology (License free)
- No paid license required
- A high-level of language
- Pure object-oriented programming language
- Developed by Sun Microsystems
- OS/Platform independent

2) What is Eclipse?

- IDE(Integrated Development Environment)/Editor
- Open source, free to use
- Used for Java development
- Although we can use it for other languages
- But purely used for Java
- Flexible for Plugins (Junit, TestNG, Maven)
- Easy to use and very user friendly

3) Data Types

- How you are representing your data
- Int, String, Character, Boolean, Double, Long

Integer

     int I = 10;
     int j = 30;
     int l = -1;
     int k = 40;

- Duplicate variables are not allowed
- The variable should be unique
- Every statement should be ended with semicolon

Double

     double d1 = 24.7;
     double d2 = 44.56;
     double d3 = 100;

Character

- character is an only single-digit value
- Should be written in single quotes

     char c = 'a'
     char d = 'b';

Boolean

     boolean b1 = true;
     boolean b2 = false;

String

- The string is a class, not a data type
- But can be used as a data type
- String s = “Hello world”;
- It is always written in double quotes
   
     String s1 = "Selenium";
     String s2 = "Java Test code";
     String s3 = "100";
     String s4 = "12.33";

- Primitive data types (int, char, boolean, double)
- Warnings are shown when a variable is declared but not used

What is System.out.println() and System.out.print()

- println() method prints the output and moves the cursor to a new line.
- Each output will be printed on a new line
- print() method prints the all output in one line