Java Unit - Ii
Java Unit - Ii
SYLLABUS
Inheritance, Packages, Interfaces and Other Topics: Understanding static, Introducing Nested and Inner
classes, Access Modifiers, Varargs: variable-Length Arguments, Lambda Expressions, garbage collection-
finalize.
Inheritance: Basics, using super, creating a multi-level hierarchy, when constructors are executed, method
overriding, polymorphism - dynamic method dispatch, using abstract class, final with Inheritance, object
class.
Packages and Interfaces: Packages, Access protection, Importing Packages, Interfaces, Default Interfaces,
Default interface methods, Use static methods in an Interface.
1
22PC1IT201 UNIT - II OOP Through Java
3) static block
1. static block used to initialize the static data member.
2. It is executed before the main method at the time of class loading.
Syntax:
static{
Body;
}
Example: Demonstrate static variables, methods, and blocks.
class UseStatic
{
static int a = 3;
static int b;
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void main (String args[])
{
meth(42);
}
}
Output:
Static block initialized.
x = 42
a=3
b = 12
2
22PC1IT201 UNIT - II OOP Through Java
Note: If you want create instance for inner class you must create instance for outer class.
3
22PC1IT201 UNIT - II OOP Through Java
2. Static nested classes (Nested class): A static class is placed into a class is called nested class.
Example:// Demonstrate an inner class.
class College{
static String name = "VNR";
public void test( ){
System.out.println("College name :"+name);
}
static class Student{
String name = "Apple";
String rollno = "22071a6901";
public void disply( ){
System.out.println("Student name :"+name);
System.out.println("Student rollno :"+rollno);
}
}
}
class Demo{
public static void main(String[] args) {
College c = new College( ); //object for outer class
c.test();
4
22PC1IT201 UNIT - II OOP Through Java
Access Modifiers
• ••
Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member.
• It provides security, accessibility, etc. to the user depending upon the access modifier used with the
element.
• There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
• When no access modifier is specified for a class, method, or data member the it having
the default access modifier by default.
• The default access modifiers are accessible only within the same package.
2. Private Access Modifier
• The private access modifier is specified using the keyword private.
• The private access modifiers are accessible only within the class in which they are declared.
• Any other class of the same package will not be able to access these members.
3. Protected Access Modifier
• The protected access modifier is specified using the keyword protected.
• The protected access modifiers are accessible within the same package or subclasses in different
packages.
4. Public Access modifier
• The public access modifier is specified using the keyword public.
• The protected access modifiers are accessible everywhere in the program. There is no restriction on
the scope of public data members
5
22PC1IT201 UNIT - II OOP Through Java
Lambda Expressions
• A lambda expression is an anonymous (i.e., unnamed) method.
• When using a lambda expression, we can provide the implementation without having to create the
method once more.
• lambda expression is used to implement a method defined by a functional interface.
• A functional interface is an interface that contains one and only one abstract method.
• A functional interface is sometimes referred to as a SAM (Single Abstract Method) type.
• Advantages are providing the implementation of Functional interface and Less coding.
• syntax: (argument-list) -> {body};
Example: Testing the number
interface NumericTest{
void test(int n);
}
class LambdaExp {
public static void main(String[] args) {
6
22PC1IT201 UNIT - II OOP Through Java
Garbage Collection
Garbage Collection
• The Garbage Collection is used to reclaim the memory of unreferenced object automatically.
• Garbage collection occurs periodically or occasionally during the execution of your program.
• How can an object be unreferenced?
➢ By nulling the reference
➢ By assigning a reference to another
➢ By anonymous object etc.
finalize( ) method:
• The finalize( ) method is invoked each time before the object is garbage collected.
• This method can be used to perform cleanup processing.
Syntax: protected void finalize( )
{
// finalization code here
}
gc( ) method:
• The gc( ) method is used to invoke the garbage collector to perform cleanup processing.
Syntax: public static void gc( ){}
class TestGarbage1
{
public void finalize( )
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1( );
TestGarbage1 s2=new TestGarbage1( );
s1=null;
s2=null;
System.gc( );
}
}
7
22PC1IT201 UNIT - II OOP Through Java
Example: A method can have variable length parameters with other parameters
class Student1{
static void result(String name, int...marks){
int sum = 0;
for(int i:marks){
sum +=i;
}
System.out.println("Student name :"+name);
System.out.println("Total Number of arguments :"+marks.length);
System.out.println("Total marks :"+sum);
} Output:
}
public class MethodOverloading { Student name :Apple
public static void main(String args[]) { Total Number of arguments :5
Student1.result("Apple",10,20,30,50,60); Total marks :170
Student1.result("Mango",60,70,80,90); Student name :Mango
} Total Number of arguments :4
} Total marks :300
8
22PC1IT201 UNIT - II OOP Through Java
Inheritance
Inheritance Basics
• Inheritance is a mechanism to obtaining the one class properties into another class and it creates new
class from existing class.
(Or)
• Inheritance is a mechanism to obtaining the one object properties into another object and it creates
new class from existing class.
• The class which is giving properties is called base class(or) parent class (or) super class.
• The class which is taking properties is called derived class (or) child class (or) sub class.
• Inheritance is basically used for reducing the overall code size of the program (code reusability).
Derived class:
• The class which is taking properties is called derived class (or) child class (or) sub class.
• Syntax:
class Derivedclass-name extends Baseclass-name
{
//data and code
}
• 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.
1. Single inheritance
Single derived class with only one base class, is called single inheritance.
(Or)
A class inherits members of only one class is called single inheritance.
Example program:
class Base {
public void add(int x, int y) {
System.out.println("Addition of x and y :"+(x+y));
}
}
class Derived extends Base {
public void sub(int x, int y) {
System.out.println("Subtraction of x and y :"+(x-y));
}
9
22PC1IT201 UNIT - II OOP Through Java
}
class SingleInheritance {
public static void main(String args[]) {
public int x = 10 , y = 20;
Derived obj=new Derived();
obj.add(x,y);
obj.sub(x,y);
}
}
Output:
Addition of x and y :30
Subtraction of x and y :-10
2. Multiple inheritance
A derived class with several base class, is called multiple inheritance.
(Or)
A class inherits members of two or more classes is called multiple inheritance.
Note: Multiple inheritance achieved through interface, not classes
Example:
interface Car{
void drive( );
}
interface Bike{
void ride( );
}
public class Person implements Car, Bike {
@Override
public void drive( ) {
System.out.println("Test drive completed by person");
}
@Override
public void ride( ) {
System.out.println("Test ride completed by person");
}
public static void main(String args[]) {
Person obj = new Person ( );
obj.drive();
obj.ride();
}
}
Output:
Test drive completed by person
Test ride completed by person
10
22PC1IT201 UNIT - II OOP Through Java
3. Hierarchical inheritance
Several derived classes with only one base class is called hierarchical inheritance.
(Or)
Two or more classes inherits members of only one class is called hierarchical inheritance.
Example program:
class Base {
int x = 10,y = 20;
public void display( ) {
System.out.println("x value:"+x);
System.out.println("y value:"+y);
}
}
class Derived1 extends Base {
public void Biggest( ) {
if(x>y)
System.out.println("biggest number is:"+x);
else
System.out.println("biggest number is:"+y);
}
}
class Derived2 extends Base {
public void mean( ) {
float z = (x + y)/2;
System.out.println("The mean of the given numbers:"+z);
}
}
class HierachielInheritance {
public static void main(String args[]) {
Derived1 obj1 = new Derived1();
obj1.display();
obj1.Biggest();
11
22PC1IT201 UNIT - II OOP Through Java
4. Multilevel inheritance
A derived class with another derived class is called multilevel inheritance.
(Or)
A class inherits members another derived class is called multilevel inheritance.
Example program:
class Base
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
}
class Derived1 extends Base
{
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
class Derived2 extends Derived1
{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
}
class MultilevelInheritance
{
public static void main(String args[])
{
int a=10, b=20;
Derived2 obj = new Derived2();
obj.addition(a, b);
obj.Subtraction(a, b);
obj.multiplication(a, b);
}
}
Output:
The sum of the given numbers:30
The difference between the given numbers:-10
The product of the given numbers:200
12
22PC1IT201 UNIT - II OOP Through Java
5. Hybrid inheritance
The combination of two or more inheritances is called hybrid inheritance.
Example:
super keyword
Output:
derived class color :black
base class color :white
15
22PC1IT201 UNIT - II OOP Through Java
POLYMORPHISM
• Polymorphism is a Greek term (poly means many and morphs means forms), polymorphism as ability to
take an object into multiple form.
• Polymorphism can be achieved by method overloading, operator overloading, and method
overloading.
• Note: Java does not support operator overloading.
• The compiler links the method call to the code (or) method definition at compile time is called compile
time polymorphism.
• In compile time polymorphism execution is fast.
• Compile time polymorphism can be achieved by method overloading, and operator overloading.
16
22PC1IT201 UNIT - II OOP Through Java
Method Overriding
• A derived class has the same method heading (return type, name, and parameters) as a method in its base
class, then the method in the derived class is said to override the method in the base class.
• Method overriding is allows a derived class to provide its own implementation for a method that is also
declared in its base class.
• This can be used to provide a specific implementation for a method that is common to all derived classes
of a particular class.
• Method overriding is a powerful feature that can be used to customize the behavior of a subclass.
Rules for method overriding:
✓ Base class and derived class method headings must be same.
✓ There must be an IS-A relationship (inheritance).
✓ If a method cannot be inherited then it cannot be overridden.
✓ Instance methods can be overridden only if they are inherited by the subclass.
✓ A method declared static cannot be overridden but can be re-declared.
✓ The method in base is need not to inherit in derived class.
Limitations:
• we cannot override main method.
• we cannot override static method.
• we cannot override final method.
Example: Demonstrate the method overriding
class Swapping1{
void swap(int a, int b){
int temp = a;
a = b;
b= temp;
System.out.println("Swapping 1 After swapping :a="+a+" and b="+b);
}
}
class Swapping2 extends Swapping1{
@Override
void swap(int a, int b){
a = a+b;
b = a-b;
a = a-b;
System.out.println("Swapping 2 After swapping :a="+a+" and b="+b);
}
}
class MethOverriding extends Swapping2{
public static void main(String[] a) {
Swapping1 s2 = new Swapping2(); //dynamic method dispatch
s2.swap(30,40);
}
}
Output:
Swapping 2 After swapping :a=40 and b=30
17
22PC1IT201 UNIT - II OOP Through Java
Abstraction
• The process of showing the functionality and hiding the implementation details is called abstraction.
(or)
• The mechanism of showing the necessary data and hiding the unnecessary data is called abstraction.
• The abstraction is achieved through abstract and interface keywords in java.
• The advantage of abstraction is readability and data hiding.
Understand abstract
• The abstract keyword is used to define abstract methods and abstract classes.
abstract method:
• A method having declaration without any implementation or body is called abstract method.
• Abstract methods are declared using abstract keyword ends with semicolon (;).
• Syntax: abstract type name(parameter-list);
abstract class:
• A class having at least one abstract method is called abstract class.
• abstract class can have member along with abstract method.
• Abstract classes can have constructors. However, it can call in concrete derived classes.
• Abstract class are defined using abstract keyword.
• Syntax: abstract class classname
{
//data & code
//abstract methods
}
Characteristics:
• All abstract method in abstract class must be implement in derived class, or else they will become
abstract too.
• We can’t create object for abstract class but create reference.
• Abstract classes are mainly used for provide an interface for its derived classes.
Limitation:
• An abstract keyword cannot be used with variables and constructors.
• We cannot use the abstract keyword with the final.
• We cannot declare abstract methods as private, and static.
• An abstract method can't be synchronized.
18
22PC1IT201 UNIT - II OOP Through Java
Output:
Before Swapping
x = 10 and y = 20
After Swapping
x = 20 and y = 10
19
22PC1IT201 UNIT - II OOP Through Java
Understand final
• The final is a keyword which is a non-access modifier used to restrict the user.
• The final keyword can be applied with the variables, methods and classes.
final class:
• When a class is declared with final keyword, it is called a final class.
• A final class cannot be inherited.
Example: Demonstrate final class
final class A{
}
class B extends A{
}
public class FinalClass {
public static void main(String args[]) {
new B();
}
}
Output: Compile time error
cannot inherit from final A
final method:
• When a method is declared with final keyword, it is called a final method.
• A final method cannot be overridden.
Example: Demonstrate final method
class A{
public final void display( ){
System.out.println("Base class display");
}
}
class B extends A{
public final void display( ){
System.out.println("Base class display");
}
}
public class FinalMethod {
public static void main(String args[]) {
new B().display();
}
}
Output: Compile time error
java: display( ) in B cannot override display() in A
overridden method is final
20
22PC1IT201 UNIT - II OOP Through Java
final Variables
• final variables are used to create constant variables.
• If you make any variable as final, you cannot change the value once it was initialized.
• You can initialize a final variable when it is declared or in constructor only.
• If your class having multiple constructors then it must be initialized in all constructor.
• A final variable that is not initialized during declaration is called blank final.
• A blank final static variable can be initialized inside a static block.
• If the final variable is a reference, then the variable cannot reference another object, but the internal
state of the object pointed by that reference variable can be changed.
• Syntax:
final <datatype> <variable name>=<value>; //final variable
final <datatype><variable name>; //blank final variable
static final <datatype><variable name>=<value>;//final static variable
Example: final double PI = 3.14;
class Final_Reference_Demo{
public static void main(String[] args)
{
final int[] arr = { 1, 2, 3, 4, 5 };
arr[4] = 1;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+”\t”);
}
}
}
Output: 1 2 3 4 1
21
22PC1IT201 UNIT - II OOP Through Java
Note:
• The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
• You may override the others.
22
22PC1IT201 UNIT - II OOP Through Java
2. Second, you can specify a directory path or paths by setting the CLASSPATH environmental
variable.
3. Third, you can use the -classpath option with java and javac to specify the path to your classes.
24
22PC1IT201 UNIT - II OOP Through Java
4. Third, you can use the -d option with java and javac to specify the path to your classes.
Importing Packages
• To use any predefined or user-defined classes that are already present in the packages, you must import
them.
to import package you need to use the import keyword.
• Syntax: import pkg1 [.pkg2].(classname | *);
• Example: import java.util.Scanner;
• There are three ways to access the package from outside the package.
1. Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
Example:
Source Code: A.java
package pack;
public class A{
public void msg( ){
System.out.println("Hello");
}
}
25
22PC1IT201 UNIT - II OOP Through Java
2. Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example:
26
22PC1IT201 UNIT - II OOP Through Java
Interfaces
• An interface is a reference type and it has static constants and abstract methods.
• The interface is a mechanism to achieve abstraction and multiple inheritance.
• An interface is a blueprint of a class. interface can specify what a class must do, but not how it does it.
• Classes that implement an interface must implement all of the methods defined in the interface except
default methods (JDK 8 onwards).
• We cannot instantiate interface like class.
• Interfaces are designed to support dynamic method resolution at run time.
• Interfaces cannot have constructors.
Defining an Interface: An interface is defined by using the interface keyword.
• Syntax:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Implementing Interfaces:
• Once an interface has been defined, one or more classes can implement that interface.
• Implement an interface using implements clause in a class definition, and then create the methods
required by the interface.
• Implements are represented by dashed line arrow (------>).
• Syntax:
class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
Limitation:
✓ A class can extends only one class.
✓ A class can implements multiple interfaces.
✓ An interface can extend multiple interfaces.
✓ An interface cannot implement another interface or class.
27
22PC1IT201 UNIT - II OOP Through Java
Output:
Rate of interest in Axis 5%
Rate of interest in SBI 7%
28
22PC1IT201 UNIT - II OOP Through Java
29
22PC1IT201 UNIT - II OOP Through Java
}
public class Person implements Vehicle {
@Override
public void drive( ) {
System.out.println("Test drive completed by person");
}
@Override
public void ride( ) {
System.out.println("Test ride completed by person");
}
public static void main(String args[]) {
Person obj = new Person ( );
obj.drive();
obj.ride();
}
}
Output:
Test drive completed by person
Test ride completed by person
30
22PC1IT201 UNIT - II OOP Through Java
Default Interfaces
An interface that contains default method is called default interface.
Default interface methods
• A default method can define a default implementation for an interface method.
• The addition of default methods does not change a key aspect of interface.
• The default methods are by the keyword default.
• Example: Demonstrate default interface method
interface RBI{
default void rateOfInterest( ){
System.out.println("Default Rate of interest is 5%");
}
}
class Axis implements RBI{ //implemented but not override
}
class SBI implements RBI{
@Override
public void rateOfInterest( ) {
System.out.println("Rate of interest in SBI 7%");;
}
}
public class DefaultMerhod {
public static void main(String args[]) { Output:
new Axis().rateOfInterest( ); Default Rate of interest is 5%
new SBI().rateOfInterest( ); Rate of interest in SBI 7%
}
}
2-Marks Question
1. Write the advantages of static keyword
2. Differentiate nested and inner class.
3. List and define access modifiers in java.
4. Differentiate private and protected.
5. What is the use of garbage collection? How to implement garbage collection in java?
6. Define varargs and write its syntax.
7. What is lambda expression and write is adavntages.
8. Define inheritance and write the syntax of derive class.
9. Write the advantages of inheritance.
10. What are the uses the super keyword.
11. Differentiate compile time and run time polymorphism.
12. What is dynamic method dispatch.
13. Define method overriding and write its rules.
14. Can we override static method? Justify your answer.
15. Write the uses of final keyword.
16. What is Object class and list some methods.
17. Define abstract method and write its syntax.
18. Define package and write its uses.
19. What are the different ways of importing packages and write its syntax?
20. What are the different ways of finding packages and write its syntax?
21. Define interface and write its uses.
22. Differentiate default interface and default interface method.
23. What is functional interface.
Essay Questions
1. How to use static keyword in JAVA? Explain with examples.
2. Define inheritance. What are the benefits of inheritance? Explain the various forms of inheritance with
suitable code segments.
3. Explain the different forms of polymorphism and explain method overriding with suitable example.
4. Illustrate the use of dynamic method dispatch with example.
5. With suitable code segments illustrate various uses of ‘final’ keyword.
6. Discuss abstract keyword with an example.
7. What is a package? How to create package? Explain with suitable example.
8. Write a short note on package and ways of importing package. Describe with appropriate example.
9. Explain about interface with suitable example.
10. What are the different ways of achieving multiple inheritance? Explain with suitable example.
32