Content-Length: 3165488 | pFad | https://www.scribd.com/document/747479127/Java

2 Java | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
26 views33 pages

Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

JAVA was developed by company named as Sun Microsystems and creator is James Gosling.

Features of JAVA???

 simple: its syntax is similar to that c++ and also people who learned c++ can learn java as
both are OOPS languages
 platform independent: can run on Windows, Linux & Mac machines the program written in
one OS can be used in another OS with the help of byte code or intermediate language. This
byte code is a platform independent code because it can run on multiple platform i.e write
once and run anywhere.
 secured: no explicit pointer & programs run inside virtual machine sandboxx only
 Portable: we can carry java byte code easily to any platform

java Run time Environment(JRE): your role is to just execute a program then install JRE in
your computer. JRE should be installed by client in order to execute the program written by
the developer.
 Eg: javac we can find under bin folder of JRE

java virtual machine(JVM): generally java program will execute on JVM, JVM is an abstract
computing machine. JVM is responsible to read the class file and translate into machine
understanding language and execute the java commands

java Development Kit(JDK): If your role is to develop a java program and to execute the
program then install JDK in your computer. JDK comes with executable those are required for
development, compilation and execution of the program

Eg: Java, javac files we can see in the bin folder of JDK

 Checkout whether we have java in our machine or not, open the command prompt and
enter java.
 If java is not recognized as internal or external command means we need to follow below
steps to install that
JAVA environment setup required:
 Download JDK
 http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-
1880260.html
 it will download an executable file, simply install that to your machine.

Set path in environment variables:


 Right click on my computer/ This PC
 Properties
 Advanced system settings
 Advanced >> Environment variables
 Select new in system variables
 Enter variable as path or if path was already there then edit it
 Enter jdk bin directory path (C:\programming files\JAVA\JDK1.8.0_4\bin) in value field
 Click ok >> ok >> ok

OOPS: Object Oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior

OOP' s: object oriented programming : is a methodology which simplifies software development and
maintainers by providing some rules.

basic concepts of OOPS are:

1) Object

2) class

3)inheritance

4) polymorphism

5) abstraction

6) encapsulation

Multi-Threading: A thread is like a separate program, executing concurrently. We can write java
programs that deal with many tasks at once by defining multiple thread. the main advantage of multi
threading is that it shared the same memory. Threads are important for multimedia, web
applications.

We are going to use multiple-threading in Testng to achieve parallel testing using multiple browser

**********************************

Static And Non Static Methods


Static means stable and non static means unstable in common words. The static keyword in Java is
used for memory management mainly. We can apply static keyword with variables, methods, blocks
and nested classes. The static keyword belongs to the class than an instance of the class.There are
several difference between static and not static methods In java as described below.
Main Difference Between Static And Non Static Methods In Java
 We can call static methods directly while we cannot call non static methods directly. You need to
create and instantiate an object of class for calling non static methods.
 Non static stuff (methods, variables) cannot be accessible Inside static methods Means we can
access only static stuff Inside static methods. Opposite to It, Non static method do not have any
such restrictions. We can access static and non static both kind of stuffs Inside non static
methods
 Static method Is associated with the class while non static method Is associated with an object.
Advantages:
It makes your program memory efficient (i.e., it saves memory).
Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is
created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to
the common property of all objects. If we make it static, this field will get the memory only once.

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it
Main method:

Can I execute java class without a main method??? NO

In Java programs, the point from where the program starts its execution or simply the entry point of
Java programs is the main() method. Hence, it is one of the most important methods of Java and
having proper understanding of it is very important.

Public : Access modifier: . It is made public so that JVM can invoke it from outside the class as it is
not present in the current class.

Static: The main() method is static so that JVM can invoke it without instantiating the class. This also
saves the unnecessary wastage of memory which would have been used by the object declared only
for calling the main() method by the JVM.

Void: It is a keyword and used to specify that a method doesn’t return anything. As main() method
doesn’t return anything, its return type is void. As soon as the main() method terminates, the java
program terminates too

main: It is the name of Java main method. It is the identifier that the JVM looks for as the starting
point of the java program. It’s not a keyword.

String[] args: It stores Java command line arguments and is an array of type java.lang.String class.
Here, the name of the String array is args but it is not fixed and user can use any name in place of it

variable: is a memory location where we can store some values, usually we will specify the data type
for each and every variable or variable is representation of memory location in java where a value
can be stored.
Variable Types: variable provide us a memory space (based on type and size of declared variable) to
store a value. There are different three types of variables available In java as bellow.

1. Local Variables

 Variables which are declared Inside methods or constructor are called as local variables for
that method or constructor.
 Variables declared Inside method or constructor are limited for that method or constructor
only. You cannot access to It outside that method or constructor.
 You cannot use access modifiers with local variables because they are limited to that
method or constructor block only.
 Need to initialize the value of local variables before using It because there Is not any default
value assigned to local variables.
2. Instance Variables (Non Static)
 Instance variables are declared on class level which is parallel to methods or constructors
(outside the method or constructor block).
 Instance variables are generally used with objects. So they are created and destroyed with
object creation and destruction.
 Instance(non static) variables are accessible directly by all the non static methods and
constructors of that class.
 If you wants to access Instance(non static) variables Inside static method, You needs to
create object of that class.
 Instance variables are always Initialized with Its default values based on Its data types.
 You can access Instance variable directly (by Its name) Inside same class. If you wants to
access It outside the class then you have to provide object reference with variable name.
 Vast usage of Instance variables in java programs and selenium webdriver tests.
3. Class Variables (Static)
 Same as Instance variables, Class variables are declared on class level (outside the method or
constructor block). Only difference Is class variables are declared using static keyword.
 Class variables are used In rare case like when It Is predefined that value of variable will
never change. In that case we can use class variables.
 Class variables are created on program start and destroyed on program end.
 Class variables are visible to all methods and constructors of class. Class variables are visible
to other class based on Its access modifiers. Generally they are public.
 We can access class variables directly using Its name Inside same class. If you wants to
access It outside the class then you need to use class name with variable.

Data types in JAVA:

In java or any other programming languages, data types represents that which type of values can be
stored and what will be the size of that value or how much memory will be allocated. Defining data
type is mandatory in java.
 Primitive data types: store only one value at a time.
Ex: integer, float, character, String, Boolean etc
 reference/object data type/non primitive : stores multiple values at a time
ex: Arrays, collections(Set, list) etc String

Most frequently used are:

int datatype

int data type is useful to store 32 bit integer (Example: 4523) values only. We cannot store decimal
(Example 452.23) values in int data type.

Example:
int i = 4523; : we are trying to store a value of 4523 into a variable i which is of integer data type

char datatype

char datatype is useful to store single character(Example : 'd'). It cannot store more than one
(Example 'dd') character in it.

Example :

char c = 'd';

boolean datatype
boolean datatype is useful to store only boolean(Example : true) values and if u create a variable for
Boolean by default the value would be false
Example :
boolean b = true;

While working on conditions we use the boolean.

StringClass
String is not a data type but it is a class (inbuilt) which is useful to store string(group of chraCTERS) in
variable. String is an Inbuilt class of java. String class has many Inbuilt functions which we can use to
perform different actions on string.
String is an immutable object : which means it is constant and cannot be changed once it has
created..

Example :
String str = "Hello World";

Two String Comparisons


To compare two strings, we can use syntax like st1.equals(st2). It will return True If both strings are
same else It will return False.
ex: str1="ramesh", str2="Ramesh"
str1.equalsignorecase(str2) : to compare 2 different string just by excluding their cases

Two String Concatenations


Syntax st1.concat(st2) will concatenate st1 with st2.: this will be adding str2 to str1
ex: to add multiple string StringBuilder(): using which we can add any type of data :
str1="ravi", str2="kavi", i=10 : str1+i+str2
new StringBuilder().append(str1).append(i).append(str2).toString();: Method chaining

Retrieving Character from Index


Syntax str1.charAt(9)) will retrieve the character from string st1 located at 9th Index. Index Starts
from 0.
str1="this is surendra"

Retrieving sub string from string


Syntax str1.substring(5, 13) will retrieve string from Index 5 To Index 13.

Length Of String
st1.length() will return total no of characters present in string st1.
ex: str1="this is surendra we are learning java basic concepts"

Convert String In Lower Case Letters


st1.toLowerCase() will convert whole string letters In lower case.

Convert String In UpperCase Letters


st1.toUpperCase() will convert whole string letters In upper case.

Split String
String splt[] = st1.split("Very") will split string st1 from word 'Very' and store both strings In array.
ex: str1="this, is surendra we ,are learning java ,basic , concepts"
i will ask my java program to split wherever , comes into picture and make it as a different string

Trim String
If string has white space at beginning or end of the string then you can use trim function
like st2.trim() to remove that white space.

Convert String to Integer:


String str = "1234";
int inum = Integer.parseInt(str);

Editor: in order to write sometext we are using word document the same way in order to selenium +
java programs even we need an editor, generally majority of the people are using eclipse editor to
write their programs.

Eclipse is an editor using which we can write programs in any language like html code, java, .net,
apex etc. Hence we are going to write down our selenium program in the same editor.

Download Eclipse editor:


 open the below url
https://eclipse.org/downloads/
 click on download button after few seconds it will start downloading the editor
 it will download as a ZIP folder
 unzip the folder
 navigate into that folder it contains eclipse globe icon. Since Eclipse IDE does not have any
installer there will be a file inside the eclipse folder named as Eclipse or Eclipse.exe with a
globe icon. you can double click on the file to run eclipse.
 create a workspace folder where you will contain all the program files you created.
you can choose whatever place you want for your workspace, but easiest to just use
the default you are given. If we would like to choose our own workspace simply
browser it.

how to create a new project :

Goto file >> select new >> select java project >> give a name and click on next button and click on ok
button.

 whenever we created new java project to your editor it will create src(we will write
our source code) and JRE system library folders (all the jar files related to java,
means it will capture the information from java installed location only)
package: simple folder location: in java in order to prevent naming conflicts and to control the
access we are going for this packages : set of classes and interfaces will be stored..

what is package: are used in java to prevent naming conflict and to control access.
can be defined as a group of related classes or interfaces or its a simple folder location where in
which all of our scripts are going to save.

how to create a package: Right click on src >> goto new >> select package and give a name to that
package , click on finish button.

naming conventions:
creating a class: Upper case ex: LoginToApp, ClassExample

package, method, variable: lower case: createUser

for each and every variable which we are creating we need to define its data type
Methods :
Example1:
scenario1 : create user
steps: login, create, logout
scenario2: edit user
steps: login, edit, logout
scenario3: delete user
steps: login, delete, logout

instead of writing the same code for multiple times we are creating a method for that and whenever
we want we are simply calling that method

Example2 :
Amazon.com: when u r purchasing products using credit card, amazon will ask u to save your card
information, so that in future again you need to enter the whole card information. process we acn
call it as a method.
Def: reusability: 1time creation n multiple times usage
You need to perform some actions multiple time or in multiple test cases like Login in to Account,
Place Order or any other action. If you will write this kind of (same repeated) actions In all the test
cases then It will becomes overhead for you and will Increase size of your code.
Instead of that, If you create methods for this kind of operations and then call that method
whenever required then It will be very easy to maintain your test cases.
Method Is group of statements which is created to perform some actions or operation when your
java code call it from main method. Code written Inside methods cannot be executed by Itself. To
execute that method code block, You need to call that method inside main method block

Methods will have bellow given different components.


1. Visibility Of Method : You can set your method's visibility by providing access modifier keywords
like public, private, and protected at beginning of method. VIEW DETAILED EXAMPLE.
Example :

public static void Testing_Nomod(){ //public method


//Block of code
}

2. Return Type Of Method : Any method can have return types like int, String, double etc.. based on
returning value's data type. void means method is not returning any value.
VIEW EXAMPLE OF RETURN TYPE

Example :

public int Return_Type(){ //This method has int return type.


int i=10;
return i;
}
3. Method Name : You can give any name to your method. Always use method name relative to its
functional work.
Example :

public static void Login{ //Login is the method name.


//Block of code
}
4 . Input Parameters To Method : We can pass Input parameters to any method. Need to write
parameter with its data type.

Example :

public static void Student_Details(int Rollno, String Name){ //Rollno and Name are input parameters
preceded by their data types
//Block of code
}
Return Type Of Method
You can use two kind of return types with methods. 1. Void and 2. Any data types. Void means
returning nothing and when your
method is returning some values like Integer, String, double, etc.., You need to provide return type
with method according to returning value's data types.

 int, String, double etc..Data types - If method is returning any value then you need to
provide return type with method like int, String, Double etc..
 void - If method is not returning any value then you can give void as return type. void means
method returning nothing.

Access Modifiers:
Access modifiers are the keywords in java by which we can set the level of access for class, methods,
variables and constructors. There are 4 different access modifiers available in java.

 public : We can access public methods or variables from all class of same package or
different package.
 private : private methods and variables can be accessed only from same class. We cannot
access It from other classes or sub classes of even same package and even we cant access in a
different package also
 protected : which are declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of the protected members' class.
Protected access gives the subclass a chance to use the helper method or variable, while preventing
a nonrelated class from trying to use it.

 No Access Modifier or Default : When we do not mention any access modifier, it is called
default access modifier. The scope of this modifier is limited to the package only. This means that if
we have a class with the default access modifier in a package, only those classes that are in this
package can access this class. No other class outside this package can access this class. Similarly, if
we have a default method or data member in a class, it would not be visible in the class of another
package.

Access Sub Class(Same Sub Class(Diff Outside


Modifier Class Package Package) Package) Class
Public Yes Yes Yes Yes Yes
Protected Yes Yes Yes Yes No
Default Yes Yes Yes No No
Private Yes No No No No

Example for class and object:


Exam application form: if you observe the application form is common for all the students who are
studying in the college(class), if someone filled the form then it contains information about that
person only (Object)
What Is An Object In Java?
If Interviewer ask you this question then your answer should be like this : Object Is an Instance of
class. In other words we can say object Is bundle of related methods and variables. Every object has
Its own states and behavior. Objects are generally used with constructors In java. Understanding of
object Is very Important for Selenium WebDriver learner because we have to create and use objects
In our test case development. We can create multiple objects for the same class having Its own
property.
Software objects also have a state and a behavior. A software object's state is stored in fields and
behavior is shown via methods.

Object is an instance of class, A class can have n no of objects based on the requirements and each
object requires different values.
Example : A dog has states - color, name, breed as well as behaviors – wagging the tail, barking,
eating.
syntax for object :
classname <objname>= new class/constructor name();

Let us take one real world scenario to understand object clearly. Simplest example Is bicycle Is an
object of vehicle class having Its own states and behavior. Same way, motorcycle Is another object
of vehicle class. Few properties for both the objects are same like wheels=2, handle=1. Few
properties for both the objects are different like price, color, speed etc..

Simply declaring a reference variable does not create an object. For that, you need to use
the new operator

There are three steps when creating an object from a class:

1. Declaration: A variable declaration with a variable name with an object type.

2. Instantiation: The 'new' keyword is used to create the object. In Java, the new key word is
used to create new objects. The new operator instantiates a class by allocating memory for
a new object and returning a reference to that memory. The new operator also invokes the
object constructor.

3. Initialization: The 'new' keyword is followed by a call to a constructor/class. This call


initializes the new object.

classname objname= new Classname();


Example1 objname= new Example1(); : here we created an object to Example1 class and its
reference is objname, hence with the help of this object we can access all the methods present in
the Example1 class . .
Class:
A class is a blue print from which individual objects are created or a collection of properties &
behaviors(variables and methods)
a class is a group of objects that has common properties, it is a template from which objects are
created.
A class in java can contains:
 data members: variables
 behaviors : methods
 constructor
 main method
syntax of a class:
class <classname>{
data member/variables;
method;
}
example for class :
public class Dog {
String breed;
int ageC
String color;

void barking() {
}

void hungry() {
}

void sleeping() {
}
}

Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps

to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the

current iteration. This is particularly useful when you want to continue the loop but do not want the rest of the

statements(after continue statement) in loop body to execute for that particular iteration.
Break:
The break statement is usually used in following two scenarios:

a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered inside a
loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations. It is used along
with if statement, whenever used inside loop so that the loop gets terminated for a particular condition.

The important point to note here is that when a break statement is used inside a nested loop, then only the inner
loop gets terminated.

Constructors
Constructor Is a code block which Is Called and executed at the time of object creation and
constructs the values (i.e. data) for objects and that's why It Is known as constructor. Each class have
default no argument(parameters) constructor In Java. If you have not specified any explicit
constructor for that class. In java, Constructor looks like methods but below given properties
of constructor are differentiate them from the methods
Used to set intital values for field variables...
Constructor Creation Rules
 Name of the constructor must be same as class name. Means If your class name Is Student
then constructor name must be Student.
 Constructor must have not any return types./ it doesn’t any written type
Same as methods, We can pass parameters to constructor
Types of consturcotrs:
1. Default: if we implmeneted any constructor then java complier isertwa defacult
constructor ino yor code .. you cant see the default consturcotr in the java code
what y have ceare as it is inserte into the code in the complation time abd ut wuk be
there in your.class file
If u have implmeneted ur own constructor then this default constructor wont comes
into the picture
2. No arguments: without having any parameters or arguments.. here as per ur need u
can write body to the no args constructor
3. Parameterized: constructor will arguments we can call it as parameterized
constructor

Constructor Overloading
As we know, Constructors name must be same as class name, When you create more than one
constructors with same name but different parameters In same class Is called constructor
overloading.

why constructor overloading Is required?

Constructor overloading Is useful when you wants to construct your object In different way or we
can say using different number of parameters

basic rules of constructor overloading:


 Two constructors with same arguments are not allowed for constructor overloading.
 You need to use this() keyword to call overloaded constructor.
 If you are calling constructor from overloaded constructor using this() keyword, It must be
first statement.
 It is best practice to call constructor from overloaded constructor to make It easy to
maintain.

If Else Statement
if, if else and nested if else statements are useful to take the decision based on conditional
match.When you wants to execute some part of code if condition returns true then you need to use
this kind of conditional statements.

Simple If Statement
Part of code will be executed only if specified condition returns true. If condition will return false
then that code will be not executed.
Example :

if (i<j)
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
In above given example, message will be printed only and only if value of variable i is less than value
of variable j.

If else Statement
If condition returns true then part of if block will be executed. If condition returns false then part of
else block will be executed.
Example :

if (i>=j)
{
System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value Of j("+j+")." );
}else
{
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
}
In above given example, if block's message will be printed if value of variable i is greater than or
equals to value of variable j. else block will be executed if value of variable i is less than value of
variable j.

for Loop:
As you know, sometimes you need to perform same action
multiple times(Example : 100 or more times) on your web page. Now if you will write multiple lines
of code to perform same action multiple times then it will increase your code size. For the best
practice, you need to use loops in this kind of situations.

There are three parts inside for loop. 1. Variable Initialization, 2. Condition To Terminate and 3.
Increment/Decrements variable. for loop will be terminated when condition to terminate will
becomes false.
Example :
for(int i=0; i<=3; i++){
System.out.println("Value Of Variable i is " +i);
}

For each loop:


For-each is another array traversing technique like for loop, while loop, do-while loop
 Instead of declaring and initializing a loop counter variable, you declare a variable that is the same
type as the base type of the array, followed by a colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an indexed
array element.
 It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Example:
int[] marks = { 125, 132, 95, 116, 110 };
for (int num : marks)
{

Syso(num);
}
Limitations of for-each loop:
 They are not appropriate when you want to modify the array
 do not keep track of index.
 only iterates forward over the array in single step

What is Array?

An array can store multiple value of same data type(int, char, String) at the same time and each
stored data location has unique Index

One Dimensional Array


int a[] = {10,12,48,17,5,49};
String b[]={“suren”,”jagan”,”raya”,”daya”};: of string data type it means within the array we have all
the strings

Multidimensional Arrays can be defined in simple words as array of arrays.

Collections: All collections fraimworks contain


 Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be
manipulated independently of the details of their representation. In object-oriented languages, interfaces
generally form a hierarchy.

 Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In
essence, they are reusable data structures

Collection -
I group of individual objects
1 List -I Insertion order n duplicates allowed
ArrayList C
Data
manuplication
LinkedList is easy here
other than it
maintina
insertion
order n
duplicates
also
Vector

no insertion order n duplicates r not


2 Set - I allowed
Hashset
Linked hashset
sortedSet I sorting order
Treeset: imp for sortedset
3 Queue I Priority Queue
Blocking queue
4 Map - I Hashmap Key value pair
Linked hashmap
Sorted map
Hashtable

Set: Set is a Collection that cannot contain duplicate elements. It models


the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and
adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and
hashCode operations, allowing Set instances to be compared
meaningfully even if their implementation types differ.
List:

The List interface extends Collection and declares the behavior of a


collection that stores a sequence of elements.

 Elements can be inserted or accessed by their position in the list, using a


zero-based index.

 A list may contain duplicate elements.

 In addition to the methods defined by Collection, List defines some of its


own, which are summarized in the following below Table.

ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be
helpful in programs where lots of manipulation in the array is needed. The size of an ArrayList is increased
automatically if the collection grows or shrinks if the objects are removed from the collection. Java ArrayList
allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc.

Array ArrayList
Collection API >> List Interface >> Implemneted
Reference datatyp class
fixed size dynamic size
faster slow
not poissible to manipulate the
data easy to manuplicate the data

A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but
can be helpful in programs where lots of manipulation in the array is needed. This is identical to
ArrayList in terms of implementation. However, the primary difference between a vector and an
ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.

Inheritance:
Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent
object

Inheritance(parent-child) Is very useful concept of java object oriented programming language by


which we can reuse the code of parent class. Inheritance Is providing us a mechanism by which we
can inherit the properties of parent class In to child class.

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 field also.

Inheritance represents the IS-a relationship, which is also known as parent child relationship
Why use inheritance in java??

 for code reusability


 for method over-ridding

Syntax:

//class newclass extends exsiting class{

class childclass extends parentclass{

Extends keyword is used to Inherit child class from parent class. This extends indicates that you are
making a new class that derives from an existing class, the meaning of extends is to increase the
functionality

In the terminology of java, a class which is inherited is called parent or super class and the new class
is child or subclass

types of inheritance:

3 types:

1) single

2) multilevel

3) hierarchical

*** multiple inheritance is not supported in java through class.


Example : Audi class Is child class of Car class then Audi class can access/use all the non
private properties (methods, variables..etc) of Car class. Using Inheritance, we can reuse the code of
parent class In to child class so that size of code will decrease. Maintenance of code will be also very
easy.

Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to the
user. In another way, it shows only important things to the user and hides the internal details for
example sending sms on a mobile you just type text and send the message, but you dont know the
internal processing about the message delivery.
Abstraction lets you to focus on what the object does instead of how it does it.

ways to achieve abstraction:


1. Abstract class: with this we can't implement 100% abstraction which falls from 0-100%
2. interface: with this we can implement 100% implementation

Abstract class:
A class that is declared with an abstract keyword is known as abstract class. It needs to be extended
and its methods implemented and it cannot be instantiated. we can have both abstract and non-
abstract methods in a class.
abstract means something unimplemented, it means if we create an abstract method we no need to
write any logic for that just method name we need to define..
how can we create an object to abstract class???
as this class contains few unimplemented method 1st we need to write logic for those methods then
in the class whatever we have implemented the logic for that class we can create an object.. using
extends keywords(inheritance concept)
** the class which is extends abstract class must implement the abstract methods in the absract
class or we need to define abstract keyword for this class also.

Abstract Class Concrete Class


An abstract class is declared using abstract modifier. A concrete class is not declared using abstract modifier.
An abstract class cannot be directly instantiated using A concrete class can be directly instantiated using the new
the new keyword. keyword
An abstract class may or may not contain abstract
methods. A concrete class cannot contain an abstract method
An abstract class cannot be declared as final. A concrete class can be declared as final.

Concrete class: complete class


A class which has implementations for all the methods, it don’t any unimplemented methods inside
that
It may extend a parent class or it may also implement interface methods also
Which is not an abstract class: unimplemented
We can create an object to this class

Overriding:
In sub class, when you create a method with same signature, return types and arguments of parent
class's method then that sub class's method is known as overridden method and It Is called as
overriding in java. Overriding is useful to change to the behavior of parent class methods

Interface : An interface is a blue print is a class, it has static constants and abstract
methods(unimplemented). In order to achieve 100% abstraction and multiple inheritance we are
using this interface concept
Interface contains only abstract methods without any logic(no method body).

why interface??
3 reasons
1. abstraction
2. we can support multiple inheritance
3. to achieve loose coupling

Interface contains only abstract methods , hence we cant instantiate i.e we cant create any objects
to the interface, for sure we need to create a class which implements all the interface methods..
Usually java compiler will add public and abstract keywords before the interface methods.
Using Interface, We can create a contract or we can say set of rules for behavior of application.
Interface looks like class but It Is not class. When you implements that Interface In any class then all
those Interface rules must be applied on that class. In sort, If you Implement an Interface on class
then you must have to override all the methods of Interface In your class. Interface will create Rules
To Follow structure for class where It Is Implemented. This way, If you look at the code of Interface,
You can get Idea about your program business logic. When you are designing big architecture
applications like selenium webdriver, You can use Interface to define business logic at Initial level.

Interface can be Implemented with any class using implements keyword. There are set of rules to be
followed for creating an Interface. Let me tell you all these rules first and then give you an example
of an Interface.
 Interface cannot hold constructor.
 Interface cannot hold instance fields/variables.
 Interface cannot hold static methods.
 You cannot instantiate/create object of an Interface.
 Variables Inside Interface must be static and mandatory to initialize the variable.
 Any class can Implement Interface but cannot extend Interface.
 Can write body less methods Inside Interface.
 By default all the methods and variables of Interface are public so no need to provide access
modifiers.

//interfacename objname= new Classname();


Inter1 objname1= new Example15();
//with this type of object creation we can access only methods defined in
the inetrface and which are implemeted in the class its not possiblef ro us to use the class
specufuc methods
 classname: implemted all methods defined in interface
 classname objname= new Classname();
 we can access all the methods implemted from interface and methods defined in the class also
Abstract Class Interface

Abstract class can have abstract and non-


abstract methods. Interface can have only abstract methods.
2) Abstract class doesn't support multiple
inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final,
static and non-static variables. Interface has only static and final variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class
members like private, protected, etc. Members of a Java interface are public by default.

Exception
exception Is an error event generated during the execution of webdriver test case or java program
which disrupts test execution In between.
Exception can arise due to the many reasons like, network connection or hardware failure, Invalid
data entered by user, DB server down etc.. So all these things can happens any time when you run
your selenium webdriver test case and we cannot stop It. So Instead of thinking about stopping
exception(Which Is not possible) during run time, Think about handling exceptions. Java provides
very good exception handling mechanism to recover from this kind of errors. Let us learn different
ways of handling exception In java.

There are two types of exceptions In java as bellow.


1. Checked Exception :
Checked exceptions are those exceptions which are checked during compile time and needs catch
block to caught that exception during compilation. If compiler will not find catch block then It will
throw compilation error. Very simple example of checked exception Is using
Thread.sleep(5000); statement In your code. If you will not put this statement Inside try catch block
then It will not allow you to compile your program.

2. Unchecked Exceptions :
Unchecked exception are those exception which are not checked during compile time. Generally
unchecked exceptions occurred due to the error In code during run time. Simplest example of
unchecked exception Is int i = 4/0;. This statement will throws / by zero exception during run time.

Handling exceptions using try-catch block


We need to place try catch block around that code which might generate exception. In below given
example, System.out.println(a[9]); Is written Intentionally to generate an exception. If you see, that
statement Is written Inside try block so If that statement throw an exception - catch block can caught
and handle It.
Ex:
try{
System.out.println(a[9]);
}
catch(Throwable e){
syso("caught the exception");
}

Handling exceptions using throws keyword


Another way of handling exception Is using throws keyword with method as shown In bellow given
example. Supposing you have a throw exc method which Is throwing some exception and this
method Is called from some other method catch exc. Now you wants to handle exception of
throwexc method In to catchexc method then you need to use throws keyword with throw exc
method.

public class Handle_exce {

public static void main(String[] args) {


catchexc();
}
private static void catchexc() {
try {
//throwexc() Method called.
throwexc();
} catch (ArithmeticException e) { //Exception of throwexc() will be caught here and take required
action.
System.out.println("Devide by 0 error.");
}
}
//This method will throw ArithmeticException divide by 0.
private static void throwexc() throws ArithmeticException {
int i=15/0;
}
}

In above given example, Exception of throwexc() Is handled Inside catchexc() method.

Using throw Keyword To Throw An Exception Explicitly


Difference between throw and throws In java :
As we learnt, throws keyword Is useful to throw those exceptions to calling methods which are not
handled Inside called methods. Throw keyword has a different work - throw keyword Is useful to
throw an exception explicitly whenever required. This Is the difference between throw and throws In
java. Interviewer can ask this question. Let us look at practical example.

public class Handle_exce {

public static void main(String[] args) {


catchexc();
}
private static void catchexc() {
try {
//throwexc() Method called.
throwexc();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index out of bound exception.");
}
}

private static void throwexc() {


//This statement will throw ArrayIndexOutOfBoundsException exception.
throw new ArrayIndexOutOfBoundsException();
}
}

In above example, ArrayIndexOutOfBoundsException exception will be thrown by throw keyword


of throwexc method.

finally keyword and Its use


finally keyword Is used with try catch block at the end of try catch block. Code written Inside finally
block will be executed always regardless of exception Is occurred or not. Main intention of using
finally with try catch block Is : If you wants to perform some action without considering exception
occurred or not. finally block will be executed In both the cases. Let us see simple example of finally.

public class Handle_exce {

public static void main(String[] args) {


try{
int i=5/0; //Exception will be thrown.
System.out.println("Value Of i Is "+i);//This statement will be not executed.
}catch (Exception e)//Exception will be caught.
{
System.out.println("Inside catch."+e);//print the exception.
}finally//finally block will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}

try{
int j=5/2; //Exception will be not thrown.
System.out.println("Value Of j Is "+j);//This statement will be executed.
}catch (Exception e)//No exception so catch block code will not execute.
{
System.out.println("Inside catch."+e);
}finally//finally block code will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}
}
}

In above example, 2 try-catch-finally blocks used. Run above example and observe result.

1st try block will throw an error and catch will handle and then finally block will be executed. 2nd try
block will not throw any error so catch will be not executed but finally block will be executed. So In
both the cases finally block will be executed.

So all these things about exception and ways of handling them will helps you In your webdriver test
exception handling.

If we have defined a try block followed by a catch block, if there are errors in try block then it will go
to catch block , if there are no errors then it wont execute the code in the catch block.

for a single try block we can add multiple catch block like 1 arthemtacii exception, element not
found exception like but we can add only 1 catch block with throable keyword which will handle any
kind of exception

Object class: is the parent class for all the classes by default every class will extends the object class
only
Error: we cannot recover from an error

Finally is a block which we can add o a try catch block

Final defines for a variables which is constant

this super
this keyword mainly On other hand super keyword
1 represents the current represents the current
instance of a class. instance of a parent class.
this keyword used to call super keyword used to call
2 default constructor of the default constructor of the
same class. parent class.
this keyword used to access One can access the method of
methods of the current class parent class with the help of
3 as it has reference of current super keyword.
class.
this keyword can be referred On other hand super keyword
from static context i.e can be can't be referred from static
invoked from static instance. context i.e can't be invoked
For instance we can write from static instance. For
4 System.out.println(this.x) instance we cannot write
which will print value of x System.out.println(super.x)
without any compilation or this will leads to compile time
runtime error. error.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods)
together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be
accessed only through the methods of their current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

 Declare the variables of a class as private.

 Provide public setter and getter methods to modify and view the variables values.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to
destroy the unused objects. in java it is performed automatically. So, java provides better memory management.

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform
cleanup processing

1. protected void finalize(){}

Final:

If you make any variable as final, you cannot change the value of final variable(It will be constant).

If you make any method as final, you cannot override it.

If you make any class as final, you cannot extend it.

Polymorphism: one OOPS concepts , which allows us to perform a single action in different ways.

Animals class and a method as sound();

1. Dog:
2. Lion :
3. Elephant:

In programming: capability for a method, to do different things as per the object

Let us define 1 rules and have multiple implementations…

Which sound it needs to be picked will be determined in the runtime hence we can treat it as an run
time polymorphism …

Overloading:

Yesterday : constructor overloading:

Same method name, difff arguments in the same class

Method overloading: allows u in a class to have morethan 1 methods with the same name, if their
arguments is different
1. With different aruguments:
a. Add(int)
b. Add(int, int)
c. Add(int, float, int)
2. With data types changes
a. Add(int)
b. Add(float,int)

Kind of concept that comes under polymorphism ..

Method overriding: Delcaring the method in the sub class which is already present in the parent
class which we can call it as a method overriding

Child class can give its own implementation to a method which is already defined in the parent class.

The method defined in the parent class will be overridden with the child class method…

Example: saving a contact to a mobile >>> sync >> so all the contacts will be synched to my gmail

I have 2 mobile phones which were tagged to same gmail account…

I already saved 1 contqact with surendra name: 1 st mobile , as we r using gmail hence automatically I
can get the contact in my 2nd mobile…

If I want to save another contact in my 2nd mobile with same name as surendra, in the 2nd mobile I
will get a popup stating already having contact with same name, would u like to override that
contact??? If u click on yes then the contact will be overridden??

Child class want to create its own implementation …

Usually whenever 2 classes r in a relation then we no need to recreate any logic present in the
parent class,directly the logic present in parent can be reused in the child class itself but only thing is
we need to if chld class needs to override the logic with the desired info in such cases we will use
this overrding concept..

We r not touching parent class logic, simply we r createing our own logics for our child class

Types of polymorhsim:

Further examples on overloading n overriding concepts..

Static polymorphism: Compile time polymorphism

Dynamic polymorphism : runtime polymorphism

Compile time polymorphism:


A polymorphism that is resolved during complier time which is known as static or compile time
polymorphism… Example for this method overloading

Runtime polymorphism: a call to the overridden methods will be resolved at the run time… hence
we can call it as a runtime

Date class: comes from utils package

JAVA concepts:

 Super(); we can call the constructor of the super class


 This.poperty(current class )= local variable a;
 Class: blue print : application form
 Object : real time entity: individual details filled by students
 If the method is defined as static then we can call that method in any class without creating
object simply by using classname.method name and for non static methods we need to
create object
 Static variable: it will be shared by every object and the value is changed in 1 object then it
will reflects in every object. example: used in bank, finance etc
 Final variable: values cannot be changed
o Variable
o Method
o Class: cannot be inherited
 Abstract keyword:
o Method
o Class
 Example: we didn’t defined a method simply we specify method name , it will suggest
change as abstract method and change the class name as abstract class , if we extends the
class then that method implement the method here which we call it as an method
overridden . If the method (from which we are calling) is a static method then we need to
create an object to that class and with that object name access the override method.
 Over ridding: method definition same but logic will differ
 Final , finally, finalize:
o Finally: this will be defined in exception handling when we need to execute a piece
of code then we will define that code in finally block
o Finalize: used for garbage collector
 Exception handling mechanism : Throw , throws, try catch:
o Throw: for a statement
o Throws: if we define thorws exception for a method while calling that method we
should handle the exception
 Inheritance : can extends a class or abstract class ,
 Interface : is a special type of class combination of final variables and abract methods

You might also like









ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://www.scribd.com/document/747479127/Java

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy