0% found this document useful (0 votes)
2 views

Java array

The document provides an overview of Java arrays, strings, and classes, detailing their characteristics, advantages, and disadvantages. It explains the syntax for declaring, instantiating, and initializing both single and multidimensional arrays, as well as various string operations and methods. Additionally, it covers the concepts of objects and classes in Java, including method declarations and types, emphasizing the importance of predefined and user-defined methods.

Uploaded by

satyasri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java array

The document provides an overview of Java arrays, strings, and classes, detailing their characteristics, advantages, and disadvantages. It explains the syntax for declaring, instantiating, and initializing both single and multidimensional arrays, as well as various string operations and methods. Additionally, it covers the concepts of objects and classes in Java, including method declarations and types, emphasizing the importance of predefined and user-defined methods.

Uploaded by

satyasri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Java array is an object which contains elements of a similar data type.

Additionally, The
elements of an array are stored in a contiguous memory location.

We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Advantages
Advertisement

o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.

Types of Array in java


There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java
1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.

class Testarray{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;//initialization a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization


Let's see the simple example to print this array.

class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5}
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column


Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

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

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Output:

123
245
445
Java Strings
In Java, a string is a sequence of characters. For example, "hello" is a
string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .

We use double quotes to represent a string in Java. For example,

String type = "Java programming";

Java String Operations


Java provides various string methods to perform different operations on
strings. We will look into some of the commonly used string operations.

Java String charAt()


The Java String class charAt() method returns a char value at the given index number.

Syntax
char charAt(int index)
example
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
Output:

1. Get the Length of a String


To find the length of a string, we use the length() method. For example,
String greet = "Hello! World";
String greet = "Hello! World";
System.out.println(greet.length());

Join Two Java Strings


We can join two strings in Java using the concat() method. For example

String first = "Java ";


String second = "Programming";
System.out.println( first.concat(second));

Compare Two Strings


In Java, we can make comparisons between two strings using
the equals() method. For example,

String first = "java programming";

String second = "java programming";

System.out.println( first.equals(second));

output

true

Java String concat


The Java String class concat() method combines specified string at the end of this
string. It returns a combined string. It is like appending another string.

String str1 = "Hello";

String str2 = "Javatpoint";

System.out.println(str1.concat(str2));

Java String equals()


The Java String class equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all characters are
matched, it returns true.

String s1="javatpoint";

String s2="javatpoint";

System.out.println(s1.equals(s2));

Output
True

Java String indexOf()


The Java String class indexOf() method returns the position of the first occurrence of
the specified character or string in a specified string.

String s1="this is index of example";

System.out.println(s1.indexOf("is"));

Output

2Java String replace()


The Java String class replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

String s1="javatpoint is a very good website";

String replaceString=s1.replace('a','e');

System.out.println(replaceString);

Output

jevetpoint is e very good website

Java String replaceAll()


The Java String class replaceAll() method returns a string replacing all the sequence of
characters matching regex and replacement string.

String s1="My name is Khan. My name is Bob. My name is Sonoo.";

String replaceString=s1.replaceAll("is","was");

System.out.println(replaceString);

Output

My name was Khan. My name was Bob. My name was Sonoo.


Java String substring()
The Java String class substring() method returns a part of the string.

1. String s1="javatpoint";
2. System.out.println(s1.substring(2,4));
3. System.out.println(s1.substring(2));

Output

va
vatpoint

Java String toLowerCase()


The java string toLowerCase() method returns the string in lowercase letter. In other
words, it converts all characters of the string into lower case letter.

String s1="JAVATPOINT HELLO stRIng";

System.out.println(s1.toLowerCase());
Output
javatpoint hello string

Java String toUpperCase()


The java string toUpperCase() method returns the string in uppercase letter. In other
words, it converts all characters of the string into upper case letter.

String s1="hello string";

System.out.println(s1.toUpperCase());
Output
HELLO STRING

StringBuffer class in Java




StringBuffer is a class in Java that represents a mutable sequence of


characters. It provides an alternative to the immutable String class,
allowing you to modify the contents of a string without creating a new
object every time.
Here are some important features and methods of the StringBuffer
class:
 StringBuffer objects are mutable, meaning that you can change the
contents of the buffer without creating a new object.
 The initial capacity of a StringBuffer can be specified when it is
created, or it can be set later with the ensureCapacity() method.
 The append() method is used to add characters, strings, or other
objects to the end of the buffer.
 The insert() method is used to insert characters, strings, or other
objects at a specified position in the buffer.
 The delete() method is used to remove characters from the buffer.
 The reverse() method is used to reverse the order of the characters in
the buffer.
Here is an example of using StringBuffer to concatenate strings:
Java
1. public class BufferTest{
2. public static void main(String[] args){
3. StringBuffer buffer=new StringBuffer("hello");
4. buffer.append("java");
5. System.out.println(buffer);
6. }
7. }
Output:

hellojava

Output
Hello world

StringBuilder Class in Java with Examples


StringBuilder in Java represents a mutable sequence of characters.
Since the String Class in Java creates an immutable sequence of
characters, the StringBuilder class provides an alternative to String Class,
as it creates a mutable sequence of characters. The function of
StringBuilder is very much similar to the StringBuffer class, as both of
them provide an alternative to String Class by making a mutable
sequence of characters. However, the StringBuilder class differs from the
StringBuffer class on the basis of synchronization.

StringBuilder Example
BuilderTest.java

1. //Java Program to demonstrate the use of StringBuilder class.


2. public class BuilderTest{
3. public static void main(String[] args){
4. StringBuilder builder=new StringBuilder("hello");
5. builder.append("java");
6. System.out.println(builder);
7. }
8. }
Output:

hellojava

Objects and Classes in Java


In this page, we will learn about Java objects and classes. In object-oriented
programming technique, we design a program using objects and classes.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.

What is an object in Java


An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of
an intangible object is the banking system.

An object has three characteristics:

Advertisement

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which


objects are created. So, an object is the instance(result) of a class.

Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Syntax to declare a class:
1. class <class_name>{
2. field;
3. method;
4. }

Java new Keyword


The new keyword creates new objects.ed
to create an inst as an object.
The new keyword in Java is used to allocate memory for the object
Create an object called "myObj" and print the value of x:
public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Method in Java
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code.

Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method
header, as we have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in
the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use
void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must
be corresponding to the functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name must be subtraction(). A
method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Naming a Method
remember that the method name must be start with a lowercase letter.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a
series of codes related to the corresponding method runs in the background that is
already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
Output:

The maximum number is: 9

User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.

How to Create a User-defined Method


Let's create a user defined method that checks the number is even or odd. First, we will
define the method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
Instance Variable
The Variables which are declared inside a class but outside of the method are
known as instance variables. Memory for instance variable are not allocated at compile time , it
will allocate at run time when the objects (instances) are created to that class. So, the variable
defined inside the class are known as instance variable.

For example:

Class Student
{
int sId;
String sname[30];
String course[];
}

Static Keyword in java

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods and blocks The static keyword belongs to the
class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block

1) Java static variable


If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.

Example of static variable


1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
}

2) Java static method


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.

Example of static method


1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }

}3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block


1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
this keyword in java

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Output:

111 ankit 5000.0


112 sumit 6000.0
Type Casting

Implicit type cast

When we assign a smaller value to another type of bigger value this type of type casting
is possible. Compiler is the responsible to perform this type casting.It is also called widening or
promotion or upcasting. In this type of typecasting there is no matter of data loss. This is also
know as automatic type casting. The following is possible in java

Example:

byte b=75;
int a =b;
are valid statements. Here the byte type is converting into integer type.

Explicit type cast

There may be situation where we assign a large variable type to small type. It is
the programmer responsibility to handle this type situation. Don't worry about this, Java provides
another way to cast large variable type to small type by using a cast operator. It looks like
following format

Type variable-1 = (Type) variable-2;

Examples:

int m=50;
byte n=(byte)m;
are valid statements in java. Here the int type is converting into byte type. In this process there
may be chance of losing data. The following are various possible conversions where explicit type
casting is required
super keyword in java
The process of inheriting or extending one class features into another class is called inheritance.
when a class extends another class, the newly created class is classed sub class and already
existing class is class super class. In inheritance process we are always create object to sub
class because the sub class contains both super class and sub class features.

If super class and sub class have same member functions, them the sub class object calls only
sub class version of the members.So, at this situation to call super class members we use "
super" keyword in java. There are three uses of super keyword

 To call the super class constructor


 To call the super class variables
 To call the super class methods.

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable


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

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class

Output:Compile Time Error

2) Java final method


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

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }

Output:Compile Time Error

3) Java final class


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

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }

Output:Compile Time Error

Java constructors
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.

1. class Bike1{
2. //creating a default constructor
3. Bike1(){System.out.println("Bike is created");}
4. //main method
5. public static void main(String args[]){
6. //calling a default constructor
7. Bike1 b=new Bike1();
8. }
9. }
Output:

Bike is created
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

1. class Student4{
2. int id;
3. String name;
4. //creating a parameterized constructor
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. //method to display the values
10. void display(){System.out.println(id+" "+name);}
11.
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
Test it Now

Output:

111 Karan
222 Aryan

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from one object
to another

In this example, we are going to copy the values of one object into another using Java
constructor.

class Student6{
1. int id;
2. String name;
3. //constructor to initialize integer and string
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student6(Student6 s){
9. id = s.id;
10. name =s.name;
11. }
12. void display(){System.out.println(id+" "+name);}
13.
14. public static void main(String args[]){
15. Student6 s1 = new Student6(111,"Karan");
16. Student6 s2 = new Student6(s1);
17. s1.display();
18. s2.display();
19. }
20. }

Output:

111 Karan
111 Karan

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the A method is used to expose the


state of an object. behavior of an object.

A constructor must not have a return


A method must have a return type.
type.

The constructor is invoked implicitly. The method is invoked explicitly.


The Java compiler provides a default
The method is not provided by the
constructor if you don't have any
compiler in any case.
constructor in a class.

The constructor name must be same as The method name may or may not be
the class name. same as the class name.

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.

Example of Constructor Overloading


1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }
Output:
111 Karan 0
222 Aryan 25

Polymorphism in java

Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

In java there are two types of polymorphism: Runtime Polymorphism and compile time
Polymorphism. Compile time Polymorphism can achieved by overloading static methods and
Runtime Polymorphism can achieved by method overloading and method overriding.

Overloading: Overloading is a OOP's concept where a method or constructor takes more than
one form by changing its signature in terms of its parameters type and number of parameters it
have.

Overriding: Overriding is a situation where a sub class and super class have same method. But
in sub class the method will perform different tasks. OR the process of writing a super class
method in sub class with same signature to achieve different task is called overriding.

Compile time Polymorphism:

Compile time Polymorphism can achieved by overloading static methods. In


java it is possible to overload static methods. Consider below example.

public class Test


{
public static void display()
{
System.out.println(" display with no parameters");
}
public static void display( int )
{
System.out.println(" display with integer parameters");
}
public static void main( String args)
{
Test.display();
Test.display(10);
The above programs gives out put as

display with no parameters


display with integer parameters
Can we override a static method in java ?

The answer is simple "NO", Because, when you define same static method in both sub class
and super class, the sub class version of static method hides super class version of method.

Runtime Polymorphism

Run time Polymorphism can achieve by overloading methods. Method overloading is


the process where you can define different with same name but different in their parameters.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.

Example:

public class Test2


{
public int add( int a , int b)
{

return(a+b);
}

public int add( int a, int b, int c)


{

return( a+b+c)
}
public static void main( String args[])
{

Test2 t= new Test2();


System.out.println(t.add(2,3));
System.out.println(t.add(2,3,4));
}

Abstract classes in java


A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java

1. Abstract class
2. Interface

Example of abstract class

3. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as
an abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract


method
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

running safely

Different types of inheritance in Java

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

Inheritance in Java is a mechanism in which deriving properties from parent class to


child class

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives
from an existing class.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can
see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:

meowing...
eating...

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

Why use Java interface?.


o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

1. nterface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output:Hello
Welcome

You might also like