JAVA UNIT-2 - Final
JAVA UNIT-2 - Final
(HAS-A), this and super, static and initialize blocks, Method overloading and
overriding, static and final keywords, Types of Inheritance, Compile time and
Runtime Polymorphism, Access Specifiers and scope, packages and access modifiers,
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
boolean - stores values with two states: true or false.
Syntax:
Method
The return type : The data type of the value returned by the method or void if does not return a value.
MethodOverloading.java
class MethodOverloading
{
void add(int a,int b)
{
int c=a+b;
System.out.println(c);
}
javac MethodOverLoading.java
java MethodOverloading
30
45.1
4.7
Constructor
Constructors are meant for initializing the object. Constructor is a special type of method that is used to
initialize object values.
Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is
why it is known as constructor.
Constructor is just like the instance method but it does not have any explicit return type.
Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor
Syntax:-
Block of statements;
...................;
...................;
..................;
..................;
};
Syntax:-
Block of statements;
...................;
...................;
..................;
..................;
};
Constructor overloading is a technique in Java in which a class can have any number of constructors
such that each constructor differ with their parameters
Student.java
class Student
{
int rollNumber;
String branchName;
Student()
{
rollNumber=100;
branchName="CSE";
System.out.println(rollNumber);
System.out.println(branchName);
}
Student(int rollNumber)
{
this.rollNumber=rollNumber;
branchName="CSE";
System.out.println(rollNumber);
System.out.println(branchName);
}
Student(int rollNumber,String branchName)
{
this.rollNumber=rollNumber;
this.branchName=branchName;
System.out.println(rollNumber);
System.out.println(branchName);
}
public static void main(String args[])
{
Student ravi=new Student();
System.out.println("-----------");
Student seetha=new Student(101);
System.out.println("-----------");
Student balu=new Student(102,"CSE");
}
Output
javac Student.java
java Student
100
CSE
-----------
101
CSE
-----------
102
CSE
Inheritance: The process of taking the features(data members and class) from one class to
another class is known as inheritance
The class which is giving the features is known as base/parentclass.
The class which is taking the features is known as derived/child/subclass.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Advantages of INHERITANCE:
I. Application development time is veryless.
II. Redundancy (repetition) of the code is reducing. Hence we can get less memory cost and
consistent results.
Types of INHERITANCES
Based on taking the features from base class to the derived class, in JAVA we have five types of
inheritances. They are as follows:
Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In
image below, the class A serves as a base class for the derived class B.
Heirarcial Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.In below image, the class A serves as a base class for the derived class B,C and D.
Multilevel Inheritance :
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class. In below image, the class A serves as a base
class for the derived class B, which in turn serves as a base class for the derived class C.
Multiple Inheritance : In Multiple inheritance ,one class can have more than one superclass
and inherit features from all parent classes.
Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not
possible with classes.
Singleinheritance.java
class Mobile_Version1
void smsservice()
System.out.println("sms service");
}
void callingservice()
void cameraservice()
System.out.println("camera service");
class Single_inheritance
m.cameraservice();
m.smsservice();
m.callingservice();
Output
sms service
calling service
Heirarcial Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.In below image, the class A serves as a base class for the derived class B,C and D.
Heirarcial_inheritance.java
class MobileVersion1
void smsservice()
System.out.println("sms service");
void calling_service()
System.out.println("calling service");
}
class MobileVersion2 extends MobileVersion1
voidcameraservice()
System.out.println("camera service");
voidfingerprint_service()
void facerecognization_service()
System.out.println("facerecognization service");
class Heirarcial_inheritance
{
MobileVersion1 m1=new MobileVersion1();
m1.calling_service();
m1.smsservice();
m2.calling_service();
m2.smsservice();
m2.cameraservice();
m3.calling_service();
m3.smsservice();
m3.fingerprint_service();
m4.calling_service();
m4.smsservice();
m4.facerecognization_service();
Output
javac Heirarcial_inheritance.java
javaHeirarcial_inheritance
calling service
sms service
calling service
sms service
camera service
calling service
sms service
calling service
sms service
facerecognization service
This Keyword
The main purpose of using this keyword is to differentiate the formal parameter and class members of
class, whenever the formal parameter and data members of the class are similar then jvm get ambiguity
To differentiate between formal parameter and data member of the class, the data member of the
class must be preceded by "this".
Student.java
class Student
int rollNumber;
String branchName;
this.rollNumber=rollNumber;
this.branchName=branchName;
System.out.println(s1.rollNumber);
System.out.println(s1.branchName);
javac Student.java
java Student
100
CSE
Super Keyword
Super keyword is placing an important role in three places. They are at variable level, at method
level and at constructor level.
Super at variable level
Whenever we inherit the base class variables into derived class, there is a possibility that
base class variables are similar to derived class members.
In order to distinguish the base class variables with derived class variables in the derived
class, the base class members will be preceded by a keyword super.
super keyword can also be used to invoke the parent class constructor
Syntax super();
MobileVersion2.java
class MobileVersion1
String modelName="Nokia1600";
int price=2000;
System.out.println("MobileVerison1 features");
System.out.println(modelName);
System.out.println(price);
int price=10000;
public void display()
System.out.println("MobileVerison2 features");
System.out.println(modelName);
System.out.println(price);
System.out.println("MobileVerison1 features");
System.out.println(super.modelName);
System.out.println(super.price);
super.display();
m1.display();
javac MobileVersion2.java
java MobileVersion2
MobileVerison2 features
Redmi 10
10000
MobileVerison1 features
Nokia1600
2000
MobileVerison1 features
Nokia1600
2000
Association
Association is relation between two separate classes which establishes through their Objects. Association
can be one-to-one, one-to-many, many-to-one, many-to-many.
Two forms of Associations are Composition and Aggregation
Aggregation vs Composition
1. Dependency: Aggregation implies a relationship where the child can exist independently of the
parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas
Composition implies a relationship where the child cannot exist independent of the parent.
Example: Human and heart, heart don’t exist separate to a Human
2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
class Author
String authorName;
int age;
String place;
this.authorName = name;
this.age = age;
this.place = place;
}
}
class Book
String name;
int price;
// author details
Author auther;
this.name = n;
this.price = p;
this.auther = auther;
System.out.println("------------Auther Details----------");
}
}
Output
javac Book.java
java Book
------------Auther Details----------
Auther Age: 42
MethodOverRiding
When super class and sub class method has same name the subclass method overrides the super class
method isknown as method over riding
same method overriding super class method with the sub class
*/
class MobileVersion1
System.out.println("5 meters");
System.out.println("10 meters");
m.hotSpot();
Output
javac MobileVersion2.java
java MobileVersion2
10 meters
Static keyword
In Java, static keyword is mainly used for memory management. It can be used with variables,
methods, blocks and nested classes. It is a keyword which is used to share the same variable or method of
a given class.
Basically, static is used for a constant variable or a method that is same for every instance of a class.
The main method of a class is generally labeled static.
In order to create a static member (block, variable, method, nested class), you need to precede its
declaration with the keyword static. When a member of the class is declared as static, it can be accessed
before the objects of its class are created, and without any object reference.
Static block
Java supports a special block, called static block which can be used for static variable initializations of a
class. This code inside static block is executed only once. Static block calling before main method
Syntax
static
//static block
Static Variable
When you declare a variable as static, then a single copy of the variable is created and divided among
all objects at the class level. Static variables are global variables. Basically, all the instances of the class
share the same static variable. Static variables can be created at class-level only.
Classname.variablename;
Static method
When a method is declared with the static keyword, it is known as a static method. The most common
example of a static method is the main( ) method.
Syntax
Classname.methodname();
class AccountHolder
long accountNumber;
static String bankName="SBI";
static
System.out.println(pinCode);
System.out.println(AccountHolder.bankName);
AccountHolder.pinCode();
Output
javac AccountHolder.java
java AccountHolder
SBI
530016
If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.
Static polymorphism is known as early binding because method invocation is determined early by the
compiler at the compile time
StaticPolymorphism.java
class StaticPolymorphism
int c=a+b;
System.out.println(c);
double c=a+b;
System.out.println(c);
s.add(10,20);
s.add(10.4,23.5);
javac StaticPolymorphism.java
java StaticPolymorphism
30
33.9
method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
dynamic polymorphism is known as late binding because method invocation is determined late at
runtime by the jvm.
MobileVersion2.java
class MobileVersion1
System.out.println("5 meters");
{
System.out.println("10 meters");
m.hotSpot();
Output
javac MobileVersion2.java
java MobileVersion2
10 meters
Final Keyword
final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a
variable, a method or a class.Following are different contexts where final is used
Final variableWhen a variable is declared with final keyword, its value can’t be modified, essentially, a
constant.
Final_Variable.java
class Final_Variable
{
Final method: when a method declared as final method cannot be overridden by the sub class
Final_Method.java
class MobileVersion1
System.out.println("5 meters");
System.out.println("10 meters");
m.hotSpot();
}
}
output
Final class: When ever a parent class declared as final class its child class or sub class cannot be inherit
the parent class
Child.java
final class Parent
{//parent class
}
class Child extends Parent
{//child class
Output
javac Final_Class.java
java Final_Class
Compile time error
Final class cannot be inherited
Access modifiers or Access specifiers in java
Access specifiers define the boundary and scope to access the method, variable, and class etc. Java has
defines four type of access specifiers such as:-
1. public
2. private
3. protected
4. default
These access specifiers are defines the scope for variables/methods. If you are not defining any access
specifier so it will be as 'default' access specifier for variables/methods.
1. public access specifier:- The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Ex:-
public int number;
2. private access specifier:-The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
3. protected access specifier:- The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. default access specifier:- Actually, there is no default access modifier; the absence of a modifier is
treated as default. The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default..
Classes belonging to other packages cannot access. That is why default access modifier is known as
package level access.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Types of packages
in java
1.built in packages:
example
import java.io.*;
import java.applet.*
import java.sql.*;
syntax:
package packagename;
javac -d . filename.java
-d creates package
how to run package program
java packagename.classname
CSE.java
package college;
class CSE
output:
javac -d . CSE.java
java College.CSE
Abstract class:
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Abstract methods: A method which is declared as abstract and does not have implementation is known as
an abstract method.An abstract method methodis an incomplete method
AbstractBankDemo.java
int withdraw=balance-debit;
}
}
class AbstractBankDemo
s.getRateOfInterest();
h.getRateOfInterest();
Output
javac AbstractBankDemo.java
java AbstractBankDemo
Interface is similar to class which is collection of public static final variables (constants) and abstract
methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
All the data members of interface are implicitly public static final.
You can not instantiate an interface which means we cannot create object directly to
interface.
Interface can not contain instance fields. Interface only contains public static final
variables.
Interface can extend multiple interfaces. It means interface support multiple inheritance
Interface Syntax:
interface <interfacename>
{
public static final datatype variablename=value;
//Any number of final, static fields
abstract returntype methodname(list of parameters or no parameters);
//Any number of abstract method declarations
}
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend another
class.
Abstract class Interface
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
4) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.
5) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".
6) A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
interface Mother
interface Father
System.out.println((Mother.height+Father.height)/2);
c.height();
}
}
javac Child.java
java Child
5.7
Interface Inheritence
BankDemo.java
interface Bank
b.withdrawService();
b.depositService();
b.loanService();
output
javac BankDemo.java
java BankDemo
java BankDemo
Class Casting
A process of converting one data type to another is known as Typecasting
In java, there are two types of casting namely up casting and down casting as follows:
Upcasting
DownCasting
Downcasting: assigning the Object or object reference of super class to the sub class reference is
known as downcasting
ClassCasting.java
class Mobile
System.out.println("smsservice");
System.out.println("camera");
}
class ClassCasting
System.out.println("Upcasting");
m.calling();
m.smsService();
System.out.println("Downcasting");
s1.camera();
s1.calling();
Output
javac ClassCasting.java
java ClassCasting
Upcasting
smsservice
Downcasting
camera
The object cloning is a way to create exact copy of an object. The clone() method of Object
class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we
want to create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
Student.java
String rollNumber;
int age;
this.rollNumber=rollNumber;
this.age=age;
return super.clone();
}
public static void main(String args[])throws CloneNotSupportedException
Student s2=(Student)s1.clone();
System.out.println(s2.rollNumber);
System.out.println(s2.age);
OUTPUT
S2 hash code=746292446
20kd1a1567
22
s2 hash code=140435067
Nested Classes:
Java nested class is a class which is declared inside the another class.
We use inner classes to logically group classes in one place so that it can be more readable and
maintainable.
advantages:
Non static nested class: non static inner class present inside outer class is known as Non static
nested class
1.regular inner class:non static inner class present inside outer classknown as regualra inner class
2.local method inner class: inner class present inside local method of outer class is known as
local method inner class
3Anonymous inner class:inner class which has no name is known as Anonymous inner class
Static inner class static class present inside the outer class is known as static inner class
Static inner can can access only static members of outer class. It cannot access non static memebrs of
outer class
static class object creation
Outer.java
class Outer
class Inner
i.m1();
javac Outer.java
Java Outer
System.out.println(x);
o.display();
java OuterClass.java
java OuterClass
10.
class Outer{
class Inner{
inobj.inMethod();
}}
outobj.outerMethod();
}}