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.

How to find XPath in Selenium WebDriver?

The Hacks of The Day
How to find XPath in Selenium WebDriver?


What is XPath? 

It is a syntax or language for finding the web elements on the web page from an XML document. XPath is used to find the location of any element on a web page using the HTML DOM structure. The Syntax for XPath: The below diagram is showing the format and elements of XPath. It helps to find the complex, dynamic web elements which are not accessible with common locator like ID, Name, CSSSelectors, etc.

XPath=//tagname[@attribute='value']

// : Select current node.
Tagname: Tagname of the particular node.
@: Select attribute.
Attribute: Attribute name of the node.
Value: Value of the attribute.

How to get XPath in Chrome: 

  1. Open the required URL in google chrome browser.
  2. Inspect the required element
  3. Right-click on the selected element
  4. Navigate to Copy -> Copy Full XPath (Absolute XPath)
  5. Navigate to Copy -> Copy XPath (Relative XPath)

Types of XPath: 

XPath has the following two types. Let's explain one by one to get deep understanding of XPath

1- Absolute XPath
2- Relative XPath 

Absolute Xpath: 

The Xpath that is used to find the element from the root node is called absolute XPath. The absolute XPath starts with a single slash(/). It contains the whole DOM structure starting from the root node to the node that we are going to find. The disadvantage of the absolute XPath is that when some changes are made in the path of the element, then that element could not be accessible anymore. Below is the example of absolute XPath.
Absolute XPath: /html/body/div[1]/div/div/form/div/div[1]/div/input

Relative XPath: 

It does not start from the root node. It starts finding the elements from the middle of the DOM structure. Double forward slash(//) is used to find the relative XPath. It can search the element anywhere on the web page. Below is the example of relative XPath.
Relative xpath: //*[@id="ui"]/div/div/form/div/div[2]/div/input
XPath finding with different locators. Given below are the possible ways to find the XPath.

1) Find By Id: 

Suppose we have the following HTML structure for an element. We can find the XPath by ID because the ID attribute is available.
Xpat h= //input[@id='email'] or we can also use as //*[@id='email']

2) Find By Name:  

If you want to find the XPath by Name attribute then the XPath expression will look like be as given below. Some time "id" attribute is not available in HTML structure for the required element. Then we can use "Name" attribute
XPath=//input[@name='email'] or we can also use as //*[@name='email']
Here is a link of the page https://ui.cogmento.com/

3) Find By Class Name: 

You can also find the XPath by Class Name. Given below is the example of XPath by Class Name.
XPath = //h2[@class='barone']

4) Find By Text() Method:

This method is used to find the element with exact text matching. In our case, we find the element with the text "Login".
XPath = //div[text()='Login']

5) Find By Contains() Method:

Contains() method is used in XPath expression to find the web elements with partial text matching. In the below example we have tried to find the element with partial text. In the XPath expression, you can see the text "Sign" in place of "Sign Up" But we can't find this element with the Text() method directly, because it only works with full-text matching.

XPath = //a[contains(text(),'Sign')] // Full Name Sign Up
Xpath = //*[contains(@type,'btn')] // Full Name btnLogin
If we use text() method with partial text as given below, it will not work.
XPath = //a[text(),'Sign')]

6) Find By Child: 

In the following XPath expression, we have found the child element "a" of the h4 tag. We can not find the "a" tag directly with the text "Java" because some other elements have the same text. So we have started with the top parent div of "a" tag.
XPath = //div[@class='g-block box4 size-24 hidden-phone']
//div[@class='g-content g-particle']//div[@class='canvas-graph']
//div[@class='canvas-middle']//h4//a[text()='Java']

7) Find By Preceding Sibling: 

In the preceding sibling, we can find the nodes that come before the current node, but the level should be the same. In some cases to find an element, we need to do some reverse engineering. We move from bottom to top to find the required element. To click in the checkbox, we will find the name that comes in front of a checkbox.
XPath = //td[text()='Tom Peter']
//preceding-sibling::td//div[@class='ui fitted read-only checkbox']
//input[@name='id']

8) Find By the Following Sibling: 

In the following sibling, we can find the nodes that come after the current node, but the level should be the same. One thing, that you should remember in the following sibling only one forward-slash (/) is used before the keyword (following-sibling). But in the case of preceding sibling double forward-slash (//) is used.
XPath = //div[@class='canvas-middle']
//a[contains(@href, 'http://www.guru99.com/accounting.html')]
/following-sibling::h4//a[text()='ACCOUNTING']

9) Find By Parent: 

It selects the parent of the current node, as shown in the below image.
XPath = //td[text()='Tom Peter']//parent::tr
//td//div[@class='ui fitted read-only checkbox']
//input[@name='id']

10) Find By Starts-with & Ends-with Methods: 

To find the XPath of the dynamic web element, whose attribute value changes on refresh, we will use either Starts-with or Ends-with method. Suppose id of an element is changing dynamically like: Id = message_123 Id = message_234 Id = message_544 So on... In the above examples, initial text is the same (message) but numerical values keep changing. So Starts-with function will be used.
XPath = //input[starts-with(@id,'message_')]
Similarly, we can use the Ends-with method. But it can be used, where the last value remains the same, and the initial value keeps changing. Suppose id of an element is changing dynamically like: Id = 234_test_t Id = 456_test_t
XPath = //input[ends-with(@id,'_test_t')]

Conclusion: 

To find the element by XPath is much more efficient as compared to other locators. That's why in complex projects, Automation Engineers prefer to use XPath for finding the elements. You can use it in a versatile way. You can find an element by moving from child to parent or parent to child. You can navigate to any direction in the HTML DOM structure. You can also control the dynamic values of web elements.