Abstraction in Java
• Abstract class
– A class that is declared with abstract keyword, is known as
abstract class in java. It can have abstract and non-abstract
methods.
– It needs to be extended and its method implemented. It cannot
be instantiated.
– Ex: abstract class A{}
• Ways to achieve Abstaction
– There are two ways to achieve abstraction in java
– Abstract class (0 to 100%)
– Interface (100%)
1
Abstraction in Java
• abstract method
– A method that is declared as abstract and does not have
implementation is known as abstract method.
– Ex: abstract void printStatus();//no body and abstract
2
Abstract class and Method
abstract class Bike
{
abstract void run(); public static void main(String
} args[])
class Hero extends Bike {
{ Hero obj = new Hero();
void run() obj.run();
{ }
System.out.println("running }
safetly...");
}
3
Example Abstract class
• Abstract class can have data member, abstract method,
method body, constructor and even main() method.
class Hero1 extends Bike
abstract class Bike {
void run()
{ {
abstract void run(); System.out.println("running safetly...");
}
void changeGear() class TestAbstraction2{
{ public static void main(String args[])
{
System.out.println("gear Bike obj = new Hero1();
changed"); obj.run();
obj.changeGear();
} }
} }
4
Abstract class Example
• Abstract class that have constructor, data member,
method body and abstract method.
class Mahindra extends motorBike
abstract class motorBike
{
{
void run()
int limit=30;
{
motorBike()
System.out.println("running safetly..");
{
}
System.out.println("constructor is
invoked");
public static void main(String args[])
}
{
void getDetails()
motorBike obj = new Mahindra();
{
obj.run();
System.out.println("it has two wheels");
obj.getDetails();
}
System.out.println(obj.limit);
abstract void run();
}
} }
5
Interface
• An Interface is a blueprint of a class.
• It contain static constants and abstract
methods.
• Interface is a mechanism to achieve
abstraction in java. There can be only
abstract methods in the interface.
• It is used to achieve abstraction and
Multiple Inheritance in java.
6
Why use Interface?
• It is used to achieve fully abstraction.
• By interface, we can support the
functionality of multiple inheritance.
• It can be used to achieve loose coupling.
7
Interface Example
• In this example, Printable Interface have only method, its
implementation is provided in the class A.
interface printable
{
void print();
}
class A implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A obj = new A();
obj.print();
}
}
8
Multiple Inheritance by Interface
• A class can extent two classes but it can implement two interface.
•
interface printable
{
void print();
} public static void main(String
interface Showable{
args[])
void show();
} {
A obj = new A();
class A implements printable, Showable obj.print();
{
obj.show();
public void print()
{ }
System.out.println("Hello"); }
}
public void show(){System.out.println("W
elcome");}
9
Interview Questions
• What is abstraction?
– Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
• What is the difference between abstraction and
encapsulation?
– Abstraction hides the implementation details whereas
encapsulation wraps code and data into a single unit.
• What is abstract class?
– A class that is declared as abstract is known as abstract class. It
needs to be extended and its method implemented. It cannot be
instantiated.
10
Interview Questions
• Can there be any abstract method without abstract
class?
– No, if there is any abstract method in a class, that
class must be abstract.
• Can you use abstract and final both with a method?
– No, because abstract method needs to be overridden
whereas you can't override final method.
• Is it possible to instantiate the abstract class?
– No, abstract class can never be instantiated.
11
Interview Questions
• What is interface?
– Interface is a blueprint of a class that have static constants and
abstract methods. It can be used to achieve fully abstraction and
multiple inheritance.
• Can you declare an interface method static?
– No, because methods of an interface is abstract by default, and
static and abstract keywords can't be used together.
• Can an Interface be final?
– No, because its implementation is provided by another class.
• Can we define private and protected modifiers for
variables in interfaces?
– No, they are implicitly public.
12
Packages
• A package is a group of similar type of class,
interface and sub-packages.
• Packages can be of two form:
• built-in package
• User-define package
• There are many built-in packages such as
java, lang, awt, javax, swing, net, io, util, sql
etc., Let us discuss about user-defined
pakages.
13
Advantage of Package
• Package is used to
categorize the
classes and interface
so they can be easily
maintained.
• Package provides
access protection.
• Package removes
naming collision.
14
Package
//save as Simple.java
package mypack;
public class Simple{
Compile java Package
public static void main(Strin • javac -d directory javafilename
g args[]){
• javac -d . Simple.java
System.out.println("Welco
Run the Package
me to package");
java mypack.Simple
}
}
15
Packages
• There are three ways to • Import keyword is
access the package from
outside the package. used to make the
– Import packages; classes and interface
– Import package.classname; of another package
– Fully qualified name. accessible to the
• If you use package.* then all current package.
the classes and interfaces of
this package will be
accessible but not sub
packages.
16
Steps to execute the package
• First create a folder in the name of pack and
mypack
• Save the Apack.java inside and outside the pack
folder.
• Save the Bpack.java file inside and outside the
mypack folder
• After compiling copy the Apack.class and
Bpack.class file in corresponding folder.
• From the main folder run the packages by giving
the command java packagename.class file name
17
Using packagename.*
package mypack;
import pack.*;
package pack;
public class A
class B
{
{
public void msg()
public static void
{
main(String args[])
{
System.out.println("Hello");
A obj = new A();
}
obj.msg();
}
}
B.java
A.java }
18
Using packagename.classname
/save by A.java //save by B.java
package pack; package mypack;
public class A import pack.A;
{ class B{
public void msg() public static void main(String args[])
{ {
System.out.println("Hello"); A obj = new A();
} obj.msg();
} }
}
19
Using fully qualified name
save by A.java //save by B.java
package pack; package mypack;
class B{
public class A{
public static void main(String arg
public void msg() s[]){
{ pack.A obj = new pack.A();//usin
System.out.println("Hello"); g fully qualified name
obj.msg();
}
}
} }
20
Interview Questions
• What is package?
– A package is a group of similar type of classes interfaces and
sub-packages. It provides access protection and removes
naming collision.
• Do I need to import java.lang package any time? Why ?
– No. It is by default loaded internally by the JVM.
• Can I import same package/class twice? Will the JVM
load the package twice at runtime?
– One can import the same package or same class multiple times.
Neither compiler nor JVM complains about it.But the JVM will
internally load the class only once no matter how many times
you import the same class.
21
Access Modifiers
• The access modifiers in java specifies
accessibility (scope) of a data member,
method, constructor or class. There are 4
types of java access modifiers:
– private
– default
– protected
– Public
22
private access modifier
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
23
default access modifier
//save by B.java
package mypack;
import pack.*;
//save by A.java
class B{
package pack;
public static void main(String args[]
class A{
){
void msg(){System.out.println("Hello
A obj = new A();//Compile Time Error
");}
}
obj.msg();//Compile Time Error
}
}
24
protected access modifier
//save by B.java
package mypack;
import pack.*;
//save by A.java
package pack;
class B extends A{
public class A{
public static void main(String args[])
protected void msg(){System.out.printl
{
n("Hello");}
B obj = new B();
}
obj.msg();
}
}
25
public access modifier
//save by B.java
package mypack;
//save by A.java
import pack.*;
package pack;
class B{
public class A{
public static void main(String args[
public void msg(){System.out.println(
]){
"Hello");}
A obj = new A();
}
obj.msg();
}
}
26
Understanding all java access
modifiers
Access within class within package outside outside
Modifier package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
27
Encapsulation
• Encapsulation in java is a process of wrapping code
and data together into a single unit, for example capsule
i.e. mixed of several medicines.
• Advantages of Encapsulation
• By providing only setter or getter method, you can make the
class read-only or write-only.
• It provides you the control over the data. Suppose you want to set
the value of id i.e. greater than 100 only, you can write the logic
inside the setter method.
28
Encapsulation
//save as Student.java //save as Test.java
public class Student class Test{
{ public static void main(String[] args
private String name; ){
public String getName(){ Student s=new Student();
return name; s.setName("vijay");
} System.out.println(s.getName());
public void setName(String name){ }
this.name=name ; }
}
}
29
Command Line Argument
• Sometimes you will want to pass information into
a program when you run it. This is accomplished
by passing command-line arguments to main( ).
• A command-line argument is the information that
directly follows the program’s name on the
command line when it is executed.
• To access the command-line arguments inside a
Java program is quite easy—they are stored as
strings in the String array passed to main( ).
30
Example
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i < args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
31
Instanceof operator
• The instance of operator is used to test
whether the object is an instance of the
specified type.
• The instanceof operator is also known as type
comparison operator because it compares the
instance with type.
• It returns either true or false.
• If we apply the instanceof operator with any
variable that have null value, it returns false.
32
Instanceof operator
• Example of instance operator where it test
the current class.
class SimpleOper
{
public static void main(String args[])
{
SimpleOper s = new SimpleOper();
System.out.println(s instanceof SimpleOper);
}
}
33
Java String
• What is string?
String is a sequence of characters. But in
java, string is an object that represents a
sequence of characters. String class is
used to create string object.
In java, string is basically an object that
represents sequence of char values.
34
String Handling in java
• In Java, a string is defined as a sequence of
characters.
• But, unlike many other languages that
implement strings as character arrays, java
implements strings as objects of type String.
• Java handles String by two classes StringBuffer
and String. The String and StringBuffer classes
are defined in java.lang.
• Thus, they are available to all programs
automatically.
35
Java Strings
• An array of characters works same as java
string. For example:
• char[] ch={‘a',‘d',‘i',‘t',‘y',‘a',‘t',‘h',‘u',‘b'};
• String s=new String(ch);
• is same as:
• String s=“adityathub";
36
Java String
• The java String is immutable i.e. it cannot
be changed but a new instance is created.
For mutable class, you can use
StringBuffer and StringBuilder class.
• How to create a String object?
• There are two ways to create String object:
– By string literal
– By new keyword
37
Java String – String Literal
• Java String literal is created by using
double quotes. For Example:
• String s="welcome";
• Each time you create a string literal, the
JVM checks the string constant pool first.
If the string already exists in the pool, a
reference to the pooled instance is
returned.
•
38
Java String – String Literal
• If string doesn't exist in the pool, a new string
instance is created and placed in the pool. For
example:
• String s1="Welcome";
• String s2="Welcome";//will not create new instan
ce
39
Java String
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
40
Java String charAt
• The java string charAt() method returns a
char value at the given index number. The
index number starts from 0.
• Signature
• The signature of string charAt() method is
given below:
• public char charAt(int index)
41
Java String charAt
public class CharAtExample{
public static void main(String args[]){
String name=“adityathub";
char ch=name.charAt(4);//returns the char value at the 4th
index
System.out.println(ch);
}}
42
Java String compare
• We can compare string in java on the basis of content
and reference.
• There are three ways to compare string in java:
• By equals() method
• By = = operator
• By compareTo() method
• String compare by equals() method
– public boolean equals(Object another)
– public boolean equalsIgnoreCase(String another)
43
Java String compare
class Teststringcomparison1{
public static void main(String args[]){
class Teststringcomparison2{
String s1="Sachin"; public static void main(String args[
String s2="Sachin"; ]){
String s3=new String("Sachin"); String s1="Sachin";
String s4="Saurav"; String s2="SACHIN";
System.out.println(s1.equals(s2));//tru
e System.out.println(s1.equals(s2));//
System.out.println(s1.equals(s3));//tru false
e System.out.println(s1.equalsIgnore
System.out.println(s1.equals(s4));//fal Case(s3));//true
se }
} }
}
44
Java String compare
String compare by == operator
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in non
pool)
}
}
45
Java String compareTo
• The java string compareTo() method
compares the given string with current
string lexicographically. It returns positive
number, negative number or 0.
• s1 > s2 => positive number
• s1 < s2 => negative number
• s1 == s2 => 0
• Signature
• public int compareTo(String anotherString)
46
Java String compareTo
public class LastIndexOfExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo"; Output:
String s4="hemlo"; 0
-5
System.out.println(s1.compareTo(s2)); -1
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}}
47
String Concatenation in Java
• String concatenation forms a new string that is the
combination of multiple strings. There are two ways to
concat string in java:
• By + (string concatenation) operator
• By concat() method
48
String Concatenation by + (string
concatenation) operator
Java string concatenation operator (+) is used to add strings. For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
49