Unit-III Methods and Inheritance in Java
Unit-III Methods and Inheritance in Java
Inheritance in Java
Mr. Shrikrishna Ulhas Kolhar
Abstraction in Java
• In object oriented programming, abstraction is defined as hiding the
unnecessary details (implementation) from the user and to focus on
essential details (functionality).
• Here, the abstract method doesn't have a method body. It may have
zero or more arguments.
Example of Abstract Method in Java
Example 1:In the following example, we will learn how abstraction is achieved using abstract
classes and abstract methods. // Regular class extends abstract class
AbstractMethodEx1.java
class AbstractMethodEx1 extends Multiply {
// abstract class
// if the abstract methods are not implemented, compiler will
abstract class Multiply {
give an error
// abstract methods
public int MultiplyTwo (int num1, int num2) {
// sub class must implement these
return num1 * num2;
methods
}
public abstract int MultiplyTwo (i
public int MultiplyThree (int num1, int num2, int num3) {
nt n1, int n2);
return num1 * num2 * num3;
public abstract int MultiplyThree
}
(int n1, int n2, int n3);
// main method
// regular method with body
public static void main (String args[]) {
public void show() {
Multiply obj = new AbstractMethodEx1();
System.out.println ("Method of ab
System.out.println ("Multiplication of 2 numbers: " + obj.Mul
stract class Multiply");
tiplyTwo (10, 50));
}
System.out.println ("Multiplication of 3 numbers: " + obj.Mul
}
tiplyThree (5, 8, 10));
obj.show();
}
}
Points to Remember
Following points are the important rules for abstract method in Java:
• An abstract method do not have a body (implementation), they just
have a method signature (declaration). The class which extends the
abstract class implements the abstract methods.
• If a non-abstract (concrete) class extends an abstract class, then the
class must implement all the abstract methods of that abstract class. If
not the concrete class has to be declared as abstract as well.
• As the abstract methods just have the signature, it needs to have
semicolon (;) at the end.
• Following are various illegal combinations of other modifiers for
methods with respect to abstract modifier:
• final
• abstract native
• abstract synchronized
• abstract static
• abstract private
• abstract strictfp
Example 2:
By default, all the methods of an interface are public and abstract. An interface cannot contain
concrete methods i.e. regular methods with body.public class AbstractMethodEx2 implements Squ
AbstractMethodEx2.java areCube {
// interface
interface SquareCube { // defining the abstract methods of interface
// abstract methods public int squareNum (int num) {
public abstract int squareNum (int n); return num * num;
// it not necessary to add public and abstrac }
t keywords public int cubeNum (int num) {
// as the methods in interface are public ab return num * num * num;
stract by default }
int cubeNum (int n);
// regular methods are not allowed in a // main method
n interface public static void main(String args[]){
// if we uncomment this method, compi SquareCube obj = new AbstractMethodEx2();
ler will give an error System.out.println("Square of number is: " + o
/*public void disp() { bj.squareNum (7) );
System.out.println ("I will give erro System.out.println("Cube of number is: " + obj.
r if u uncomment me"); cubeNum (7));
} }
*/ }
}
Abstract class in Java
A class which is declared as abstract is known as an abstract
class. It can have abstract and non-abstract methods. It needs
to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
• An abstract class must be declared with an abstract
keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
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.
Output:
running safely
Understanding the real scenario of Abstract class
• In this example, Shape is the abstract class, and its
implementation is provided by the Rectangle and Circle
classes.
//
Java Program to demonstrate the way of passi
ng an anonymous array
//to method.
public class TestAnonymousArray{
//
creating a method which receives an array as
a parameter
static void printArray(int arr[]){ Output:
for(int i=0;i<arr.length;i++) 10
System.out.println(arr[i]); 22
} 44
66
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//
passing anonymous array to method
Multidimensional Array //
in Java Java Program to illustrate the use of multidimensio
In such case, data is stored nal array
in row and column based class Testarray3{
public static void main(String args[]){
index (also known as matrix
//declaring and initializing 2D array
form). int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
Syntax: dataType[] for(int i=0;i<3;i++){
[] arrayRefVar; (or) for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
dataType []
}
[]arrayRefVar; (or) System.out.println();
dataType arrayRefVar[] }
[]; (or) }}
Output
dataType []arrayRefVar[]; 123
245
445
Example to instantiate
Multidimensional Array
in Java
Java String
In Java, string is basically an object that represents sequence of
char values. An array of characters works same as Java string.
For example:
char[] ch={'j','a','v','a',’s',’u',’b’,’j',’e’,’c’,'t'};
String s=new String(ch);
is same as:
String s="javasubject";
CharSequence Interface
• The CharSequence interface is used to represent the sequence of
characters.
• String, StringBuffer and StringBuilder classes implement it. It means,
we can create strings in Java by using these three classes.
• The Java String is immutable which means it cannot be changed.
Whenever we change any string, a new instance is created.
• For mutable strings, you can use StringBuffer and StringBuilder classes.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String class
is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal 2. By new keyword
1) 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 (special memory In this example, only one object
area)" first. If the string already exists in the pool, will be created. Firstly, JVM will
not find any string object with
a reference to the pooled instance is returned. If the value "Welcome" in string
constant pool that is why it will
the string doesn't exist in the pool, a new string create a new object. After that
instance is created and placed in the pool. For it will find the string with the
value "Welcome" in the pool, it
example: will not create a new object but
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
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);
Output:
}}java The above code, converts
a char array into a String object. And
strings
displays the String objects s1, s2,
example
and s3 on console
using println() method.
No. Method Description
1 char charAt(int index) It returns char value for the particular index
2 int length() It returns string length
3 static String format(String format, Object... args) It returns a formatted string.
4 static String format(Locale l, String format, Object... args) It returns formatted string with given locale.
5 String substring(int beginIndex) It returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin index and end index.
7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char
value.
8 static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? extends CharSe It returns a joined string.
quence> elements)
10 boolean equals(Object another) It checks the equality of string with the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the specified CharSequence.
15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.
16 String[] split(String regex) It returns a split string matching regex.
17 String[] split(String regex, int limit) It returns a split string matching regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given
index.
21 int indexOf(String substring) It returns the specified substring index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring index starting with given
index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase using specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase using specified locale.
27 String trim() It removes beginning and ending spaces of this string.
28 static String valueOf(int value) It converts given type into string. It is an overloaded method.
Wrapper classes in Java
• The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature convert primitives
into objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and vice-
versa
Use unboxing.
of Wrapper classes in Java
• Java is an object-oriented programming language, so we need to deal with objects
many times like in Collections, Serialization, Synchronization, etc. Let us see the
different scenarios, where we need to use the wrapper classes.
• Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.
• Synchronization: Java synchronization works with objects in Multithreading.
• java.util package: The java.util package provides the utility classes to deal with
objects.
• Collection Framework: Java collection framework works with objects only. All
The eight classes of the java.lang package are known as wrapper classes
in Java. The list of eight wrapper classes are given below:
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
• The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char
to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
• Since Java 5, we do not need to use the valueOf() method of wrapper
classes to convert the primitive into objects.
//
Java program to convert primitive into objects
Output
//Autoboxing example of int to Integer 20 20 20
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//
converting int into Integer explicitly
Integer j=a;//
autoboxing, now compiler will write Integer.va
lueOf(a) internally
Unboxing
• The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing.
• Since Java 5, we do not need to use the intValue() method of wrapper
//classes to convert the wrapper type into primitives.
Java program to convert object into pr
imitives
Output
//Unboxing example of Integer to int 333
public class WrapperExample2{
public static void main(String args[]
){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//
converting Integer to int explicitly
int j=a;//
//
Autoboxing: Converting primitives into obje
// cts
Java Program to convert all primitives into Byte byteobj=b;
its corresponding Short shortobj=s;
//wrapper objects and vice-versa Integer intobj=i;
public class WrapperExample3{ Long longobj=l;
public static void main(String args[]){ Float floatobj=f;
byte b=10; Double doubleobj=d;
short s=20; Character charobj=c;
int i=30; Boolean boolobj=b2;
long l=40;
float f=50.0F; //Printing objects
double d=60.0D; System.out.println("---
char c='a'; Printing object values---");
boolean b2=true; System.out.println("Byte object: "+byteobj);
The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to
increase the functionality.
• Constructors in Java are used to initialize the values of the attributes of the object
serving the goal to bring Java closer to the real world.
Note: In Java, constructor of the base class with no argument gets automatically
called in the derived class constructor.
// Java Program to Illustrate Invocation of
Constructor Calling Without Usage of super
Keyword // Class 3
// Main class
// Class 1 Super class class GFG {
class Base { // Main driver method
// Constructor of super class public static void main(String[]
Base() args)
{
{
// Print statement
System.out.println( // Creating an object of sub
"Base Class Constructor Called "); class
} // inside main() method
// Class 2 Derived d = new Derived();
// Sub class // Note: Here first super
class Derived extends Base { class constructor will be
// called there after
// Constructor of sub class derived(sub class)Outputconstructor
Derived() // will beBase called
Class Constructor Called
{ } Derived Class Constructor Called
// Print statement }
System.out.println( Output Explanation: Here first superclass
"Derived Class Constructor Called constructor will be called thereafter derived(sub-
"); class) constructor will be called because the
}
constructor call is from top to bottom.
}
// Java Program to Illustrate Invocation of
Constructor Calling With Usage of super Keyword
// Class 3 Main class
// Class 1 Super class
class Base {
public class GFG {
int x; // Main driver method
// Constructor of super class public static void main(String[] args)
Base(int _x) { x = _x; } {
} // Creating object of sub class
// Class 2 Sub class // inside main() method
class Derived extends Base { Derived d = new Derived(10, 20);
int y;
// Invoking method inside main()
// Constructor of sub class
Derived(int _x, int _y) method
{ d.Display();
// super keyword refers to super class }
super(_x); } Output
y = _y; x = 10, y = 20
}
// Method of sub class
Here we call a parameterized constructor of
void Display()
{
the base class using super(). The point to
// Print statement note is base class constructor call must
System.out.println("x = " + x + ", y = " be the first line in the derived class
+ y); constructor.
}
} Implementation: super(_x) is the first line-
Method Overriding in Java
• If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
• In other words, If a subclass provides the specific implementation
of the method that has been declared by one of its parent class, it
is known as method overriding.