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

4305 - File - JAVA - Notes (Unit 2)

Uploaded by

ajith channel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
230 views

4305 - File - JAVA - Notes (Unit 2)

Uploaded by

ajith channel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

SRI KALISWARI COLLEGE (Autonomous), SIVAKASI

DEPARTMENT OF COMPUTER APPLICATIONS


CORE COURSE – V: JAVA PROGRAMMING (23UCAC31)

UNIT – II
Inheritance: Basic Concepts – Types of Inheritance – Member Access Rules –
Usage of This and Super Key Word – Method Overloading – Method Overriding –
Abstract Classes – Dynamic Method Dispatch – Usage of Final Keyword. Packages:
Definition – Access Protection – Importing Packages. Interfaces: Definition –
Implementation – Extending Interfaces. Exception Handling: Try – Catch – Throw –
Throws – Finally – Built–in Exceptions – Creating Own Exception Classes.

Inheritance
 It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class.
 A class that inherits from another class can reuse the methods and fields of that
class.
 Inheritance is a key feature of OOP
 The extends keyword is used for inheritance in Java
Features of Inheritance
Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details, is
achieved through inheritance. Abstraction only shows the functionality to the user.
Syntax
class DerivedClass extends BaseClass
{
//methods and fields
}
Example
import java.io.*;
class Employee {
int salary = 60000;
}

[1]
class Engineer extends Employee {
int benefits = 10000;
}
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary + "\nBenefits : " + E1.benefits);
}
}
Types of Inheritance
There are 5 different types of inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
 In single inheritance, a sub-class is derived from only one super class.
 It inherits the properties and behavior of a single-parent class.

[2]
Example
import java.io.*;
import java.lang.*;
import java.util.*;
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}
class Two extends One {
public void print_for() {
System.out.println("for");
}
}
public class Main {
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
2. Multilevel Inheritance
 In Multilevel Inheritance, a derived class will inherit a base class, and as well as
the derived class also acts as the base class for other classes.

[3]
Example
import java.io.*;
import java.lang.*;
import java.util.*;
class One {
public void print_geek() {
System.out.println("Geeks");
}
}
class Two extends One {
public void print_for() {
System.out.println("for");
}
}
class Three extends Two {
public void print_lastgeek() {
System.out.println("Geeks");
}
}
public class Main {
public static void main(String[] args) {
Three g = new Three();
g.print_geek();
g.print_for();
g.print_lastgeek();
}
}
3. Hierarchical Inheritance
 In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass.

[4]
Example
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"); }
}
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
obj_D.print_A();

[5]
obj_D.print_D();
}
}
4. Multiple Inheritance
 Java does not support multiple inheritances with classes
 In Java, we can achieve multiple inheritances only through Interfaces.

5. Hybrid Inheritance
 It is a mix of two or more of the above types of inheritance.
 Since Java doesn’t support multiple inheritances with classes, hybrid inheritance
involving multiple inheritance is also not possible with classes.
*******************************
Member Access Rules in Java (or) Access Modifiers
 Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default
 When no access modifier is specified then It is called as default.
 Accessible only within the same package.
2. Private
 The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the
class
 Any other class of the same package will not be able to access these members.

[6]
Example
package p1;
class A {
private void display()
{
System.out.println("GeeksforGeeks");
}
}
class B {
public static void main(String args[])
{
A obj = new A();
// Trying to access private method of another class
obj.display();
}
}
3. Protected
 The protected access modifier is specified using the keyword protected.
 The methods or data members declared as protected are accessible within the
same package or subclasses in different packages.
4. Public
The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access
modifiers.
 Classes, methods, or data members that are declared as public are accessible
from everywhere in the program.
************************
This Keyword
 In Java, this is a reference variable that refers to the current object.
Usage of this Keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)

[7]
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.
Example
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
***********************
Super Keyword
 The super keyword in Java is a reference variable that is used to refer the
immediate parent class object.

[8]
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1. super can be used to refer immediate parent class instance variable.
 super keyword to access the data member or field of parent class.
 It is used if parent class and child class have same fields.
Example
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
2. super can be used to invoke immediate parent class method.
 super keyword can also be used to invoke parent class method.
 It should be used if subclass contains the same method as parent class.
Example
class Animal{
void eat(){System.out.println("eating...");}
}

[9]
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}
3. super() can be used to invoke immediate parent class constructor
 super keyword can also be used to invoke the parent class constructor.
Example
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

***********************

[10]
Method Overloading in JAVA
Method Definition – Refer Unit 1 Notes
 Same function name with different parameters is called method overloading
 When a method is called, Java decides which version to execute based on the
parameters.
 Method overloading in Java is also known as Compile-time Polymorphism,
Static Polymorphism, or Early binding.
Different Ways of Method Overloading in Java
1. Changing the Number of Parameters.
2. Changing Data Types of the Arguments.
3. Changing the Order of the Parameters of Methods
1. Changing the Number of Parameters
 Method overloading can be achieved by changing the number of parameters
while passing to different methods
Example
import java.io.*;
class Product {
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}
public int multiply(int a, int b, int c)
{
int prod = a * b * c;
return prod;
}
}
class GFG {
public static void main(String[] args)
{
Product ob = new Product();

int prod1 = ob.multiply(1, 2);


System.out.println("Product of the two integer value :" + prod1);

int prod2 = ob.multiply(1, 2, 3);


System.out.println("Product of the three integer value :" + prod2);
}
}

[11]
2. Changing Data Types of the Arguments

 Methods can be considered Overloaded if they have the same name but have
different parameter types, methods are considered to be overloaded.
Example
import java.io.*;
class Product {
public int Prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}
public double Prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}

class GFG {
public static void main(String[] args)
{
Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);


System.out.println("Product of the three integer value :" + prod1);

double prod2 = obj.Prod(1.0, 2.0, 3.0);


System.out.println("Product of the three double value :" + prod2);
}
}

3. Changing the Order of the Parameters of Methods

 Method overloading can also be implemented by rearranging the parameters of


two or more overloaded methods.
Example
import java.io.*;
class Student {
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " "
+ "Roll-No :" + roll_no);
}
public void StudentId(int roll_no, String name)

[12]
System.out.println("Roll-No :" + roll_no + " "+ "Name :" + name);
}
}
class GFG {
public static void main(String[] args)
{
Student obj = new Student();
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
}
}

**********************
Method Overriding in Java
Method Defintion – Refer Unit 1 Notes
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
Rules for Java Method Overriding

1) Final methods cannot be overridden


 If we don’t want a method to be overridden, we declare it as final.
Example
class Parent {
// Can't be overridden
final void show() {}
}

class Child extends Parent {


// This would produce error
void show() {}
}
2) Static methods cannot be overridden
 When you define a static method with the same signature as a static method in
the base class, it is known as method hiding.
Example

class Parent {
static void m1()
{
System.out.println("From parent "+ "static m1()");
}
void m2()
{
System.out.println("From parent "+ "non - static(instance) m2() ");
}
}
[13]
class Child extends Parent {
static void m1()
{
System.out.println("From child static m1()");
}
@Override public void m2()
{
System.out.println(
"From child "
+ "non - static(instance) m2() ");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Child();
obj1.m1();

// Here overriding works


// and Child's m2() is called
obj1.m2();
}
}
******************

Abstract Class

 Abstraction is a process of hiding the implementation details and showing only


functionality to the user.
 A class declared with the abstract keyword is known as an abstract class.
 It can have abstract and non-abstract methods
 An abstract class must be declared with an abstract keyword.
 It cannot be instantiated.
 It can have constructors and static methods
Abstract Method
 A method which is declared as abstract and does not have implementation is
known as an abstract method.
Example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely");
}
[14]
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

****************
Final Keyword
 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

1. Final Variable
 If you make any variable as final, you cannot change the value of final variable

Example
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; // Displays Compile Time error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
2. Final Methods
 If you make any method as final, you cannot override it.
Example
class Bike{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
[15]
3. Final Class
 If you make any class as final, you cannot extend it.
Example
final class Bike{}
class Honda1 extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
**********************
Packages
 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.
Advantages of JAVA Packages
1) Java package is used to categorize the classes and interfaces
2) The Java package provides access protection.
3) Java package removes naming collision
Create a Package in Java
1. Choose a Package Name: Select a meaningful and unique name for your
package.
2. Create a Directory Structure: Create a directory structure that matches your
package name in your file system.
3. Place Your Classes: Put the Java classes that belong to your package in the
corresponding directory.
4. Declare the Package: At the beginning of each Java file, you must declare the
package to which the class belongs. Use the package keyword followed by the
package name.

[16]
5. Compile and Use: Compile your Java code using the javac command. You can
then use the classes in your package by importing them into other Java files using
the import statement.
Types of Packages in Java
 There are 2 types
1. Built – in Packages
2. User – Defined Packages
1. Built – in Packages
 These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:
a) java.lang: Contains language support classes(e.g classes which defines primitive
data types, math operations). This package is automatically imported.
b) java.io: Contains classes for supporting input / output operations.
c) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
d) java.applet: Contains classes for creating Applets.
e) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc). 6)
f) java.net: Contain classes for supporting networking operations.
2. User – Defined Packages
 These are the packages that are defined by the user.
 First we create a directory myPackage (name should be same as the name of the
package).
 Then create the MyClass inside the directory with the first statement being the
package names.
Example
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}

**********************

Importing Packages in Java


 To use classes from a package in your Java code, you need to import them using
the ‘import’ statement.
 Here is a Java package example of how you can do it:

[17]
import package_name.class_name;
 For example, if you have a class named ‘MyClass’ in the package
‘com.example.myapp’, you would import it like this:
import com.example.myapp.MyClass;
 Once imported, you can create instances of the imported class and use its
methods and fields in your code.
 We can Import One Specific Class From a Package as follows
import java.util.scanner
 We can Import One Whole Package as follows
import java.util.*
 * denotes all the classes from the util package

***********************
Interfaces
 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.
 We cannot create objects for interface.
 One interface can extend from another interface
 Many number of classes can implement the interface using the keyword
“implements”.
Why use Java interface?
 There are mainly three reasons to use interface. They are given below.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
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
interface <interface_name>{
//Methods
}
Example
interface printable{
void print();
}

Extending Interface
 An interface contains variables and methods like a class but the methods in an
interface are abstract by default.
 An interface extends another interface like a class
[18]
 extends keyword is used to extend the interface.
Example
interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
public void funcB() {
System.out.println("This is funcB");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}
}

Output
This is funcA
This is funcB
Explanation
 The interface A has an abstract method funcA().
 The interface B extends the interface A and has an abstract method funcB().
 The class C implements the interface B.
 In the method main() in class Demo, an object obj of class C is created.
 Then the methods funcA() and funcB() are called
*******************
Multiple Inheritance in Java Using Interface
 Multiple Inheritance is an OOPs concept that can’t be implemented in Java using
classes.
 But we can use multiple inheritances in Java using Interface.

[19]
Example
interface API {
default void show()
{
System.out.println("Default API");
}
}
interface Interface1 extends API {
void display();
}
interface Interface2 extends API {
void print();
}

class TestClass implements Interface1, Interface2 {


public void display()
{
System.out.println("Display from Interface1");
}
public void print()
{
System.out.println("Print from Interface2");
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.show();
d.display();
d.print();
}
}

********************

Exception Handling in JAVA


 The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors

What is Exception in Java?


 In Java, an exception is an event that disrupts the normal flow of the program.
 It is an object which is thrown at runtime.

Types of Java Exceptions


 There are mainly two types of exceptions: checked and unchecked.
 An error is considered as the unchecked exception.
1. Checked Exception
2. Unchecked Exception

[20]
1. Checked Exception
 The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions.
 For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
2. Unchecked Exception
 The classes that inherit the RuntimeException are known as unchecked
exceptions.
 For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
 Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
Java Exception Keywords
 Java provides five keywords that are used to handle the exception. The following
table describes each.

Built – in Exception
 Built-in exceptions are the exceptions that are available in Java libraries.
 These exceptions are suitable to explain certain error situations.
 Some of the Built-in Exceptions are listed below,
1. ArithmeticException

[21]
2. ArrayIndexOutOfBoundsException
3. IllegalArgumentException
4. NegativeArraySizeException
5. NullPointerException
6. NumberFormatException
7. ClassNotFoundException
8. NoSuchMethodException
Example – Refer lab note program

User – Defined Exception


 The Exception which is created on our own is called user defined exception.

Example – Refer Lab Note

*******************************

[22]

You might also like