Java Unit 3 Notes
Java Unit 3 Notes
Java Unit 3 Notes
UNIT – 3
Inheritance
Inheritance in Java: inheritance is an important pillar of OOP. It is the mechanism in Java by
which one class is allow to inherit the features( fields and methods) of another class.
Important terminologies
Super class: the class whose features are in a rated is known as super class or a base class are a
parent class.
Subclass: the class that inherits the other class is known as subclass or a derived class, extended
class or child class. The subclasses can add its own fields and methods in addition to the
superclass fields and methods.
Re usability: inheritance supports the concept of reusability. that is, when we want to create a
new class and there is already a class that include some of the code that we want, we can derive
our own class from the existing class by doing this, we are reusing the fields and methods of the
existing class.
syntax
class derived- class extends- base class
{
// methods and fields
}
int height;
Bedroom(int x,int y,int z)
{
super(x,y);
height=z;
}
int volume()
{
return(lengh * breadth);
}
}
}
class Inhertest
{
public static void main(string args[])
{
int area1=room1.area();
int volume1=room1.volume;
System.out,println(“Area1=”+area);
System.out.println(“Volume1=”+volume);
}
}
Types of inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In
the image below, class A serves as a base class for the derived class B.
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
class A
{
public void print_A() { System.out.println("Class A"); }
}
class B extends A
{
public void print_B() { System.out.println("Class B"); }
}
class C extends A
{
public void print_C() { System.out.println("Class C"); }
}
class D extends A
{
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have
more than one superclass and inherit features from all parent classes. Please note that Java does
not support multiple inheritances with classes. In java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interface A and B.
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Example
class A
{
void msg()
{
System.out.println(“Hello”);
}
class B
{
void msg()
{
System.out.println(“Welcome”);
}
class C extends A,B //multiple inheretence
{
Public Static void main(String args[])
{
C.obj=new C();
obj.msg();// now which method msg() would be invoked?
}
}
Polymorphism in Java is a concept by which we can perform a single action in 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.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism.
Method overloading:
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
Example:
void gfgcw() {........}
void gfgcw(int num1) {........}
void gfgcw(float num1) {........}
void gfgcw(int num1,float num2) {........}
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder
class TestOverloading1
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
class TestOverloading2{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
Operator overloading:
An operator is said to be overloaded if it can be used to perform more than one function.
Operator overloading is overloading method in which an existing operator is given a new
meaning in Java + operator is overloaded. Java, on the other hand, does not allow for user-
defined operator overloading. To add integer, + can be employed as an arithmetic addition
operator. It can also be used to join string together.
example
int sum=a+b;
Stringcon_str=s1+s2;
obj.add(10,10);
obj.add(“Operator”,”overloading”);
1. Get improves call clarity and allows for the use of a single name for several
procedures
2. it as a faster execution time since i....ered early in the compilation process.it as a faster
execution time since it is discovered early in the compilation process
Upcasting : Overriding is done by using a reference variable of the superclass. The method to
be called is determined based on the object which is being referred to by the reference
variable. This is also known as Upcasting.
Upcasting takes place when the Parent class’s reference variable refers to the object of the
child class. For example:
class A{}
class Bike
void run()
System.out.println(“running”);
void run()
b.run();
Dynamic binding:
What is binding?
Connecting a method call to the method body is known as binding.
Understanding Type
Let's understand the type of instance.
1) variables have a type
data variable is a type of int.
Static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
class Dog
{
private void eat()
{
System.out.println("dog is eating...");
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes
the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now
generics force the java programmer to store a specific type of objects.
1.Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
Without Generics, we can store any type of objects.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Let's see a simple example to create and use the generic class.
class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());
}}
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Generic Method
Like the generic class, we can create a generic method that can accept any type of arguments.
Here, the scope of arguments is limited to the method where it is declared. It allows static as well
as non-static methods.
Let's see a simple example of java generic method to print array elements. We are using here E
to denote the element.
Instance of operator
The instanceof operator in Java is used to check whether an object is an instance of a particular
class or not.
Its syntax is
objectName instanceOf className;
Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns
false.
class Main
{
public static void main(String[] args)
{
// create a variable of string type
String name = "Programiz";
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
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.
It can have final methods which will force the subclass not to change the body of the method.
Interface
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.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Syntax:
interface <interface_name>{
Interface Example
In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Example
class Animal{
String color="white";
String color="black";
void printColor(){
class TestSuper1{
d.printColor();
}}
Packages in java
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Example
/save as Simple.java
package mypack;
System.out.println("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
obj.msg();
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
class B{
obj.msg();
Output:Hello
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular
group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related classes in io package,
Server and ServerSocket classes in net packages and so on.
Example of Subpackage
package com.javatpoint.core;
class Simple{
System.out.println("Hello subpackage");
Output:Hello subpackage
Java.util Package
It contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).
AbstractList: This class provides a skeletal implementation of the List interface to minimize the
effort required to implement this interface backed by a “random access” data store (such as an
array).
AbstractSet: This class provides a skeletal implementation of the Set interface to minimize the
effort required to implement this interface.
Arrays: This class contains various methods for manipulating arrays (such as sorting and
searching).
Calendar: The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting
the date of the next week.
Collections: This class consists exclusively of static methods that operate on or return
collections.
Date: The class Date represents a specific instant in time, with millisecond precision.
Dictionary<K,V>: The Dictionary class is the abstract parent of any class, such as Hashtable,
which maps keys to values.
EnumMap,V>: A specialized Map implementation for use with enum type keys.
EventListenerProxy: An abstract wrapper class for an EventListener class which associates a set
of additional parameters with the listener.
EventObject: The root class from which all event state objects shall be derived.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap
instance).
Hashtable<K,V>: This class implements a hash table, which maps keys to values.
IdentityHashMap<K,V>: This class implements the Map interface with a hash table, using
reference-equality in place of object-equality when comparing keys (and values).
LinkedHashMap<K,V>: Hash table and linked list implementation of the Map interface, with
predictable iteration order.
LinkedHashSet: Hash table and linked list implementation of the Set interface, with predictable
iteration order.