Java Unit II Notes.docx
Java Unit II Notes.docx
- Types of Inheritance:
1) Single Inheritance
2) Multi-level Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance
- We use following syntax for creating the new class from old class. class
DerivedClassName extends BaseClassName
{
//body of Derived Class
}
1) Single Inheritance:
- This is one of the types of inheritance.
- To create new class from only one base class is known as single
inheritance.
- Syntax:
2) Multi-level Inheritance:
- The mechanism of deriving the class from another derived class is known
as multi-level inheritance.
- To create new class from another derived class is known as multi-level
inheritance.
- It is one of the types of inheritance.
- Syntax:
class BaseClass1
{
//body of BaseClass1 Class
}
class DerivedClass1 extends BaseClass1
{
//body of DerivedClass1
}
class DerivedClass2 extends DerivedClass1
{
//body of DerivedClass2
}
-Example
//Multi-level Inheritance
import java.util.*;
class Student
{
int rollno;
String name;
void get_stud_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno=sc.nextInt();
System.out.println("Enter Student Name:");
name=sc.next();
}
void disp_stud_info()
{
System.out.println("Student ROll No:"+rollno);
System.out.println("Student Name:"+name);
}
}
class Test extends Student
{
int marks1,marks2;
void get_stud_marks()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1=sc.nextInt();
System.out.println("Enter Student Test-2 Marks:");
marks2=sc.nextInt();
}
void disp_stud_marks()
{
System.out.println("Test-1 Marks:"+marks1);
System.out.println("Test-2 Marks:"+marks2);
}
}
class Result extends Test
{
int total_marks;
void get_total_marks()
{
total_marks=marks1+marks2;
}
void disp_total_marks()
{
System.out.println("Total Marks:"+total_marks);
}
}
class MultilevelInheritanceDemo
{
public static void main(String args[])
{
Result t1=new Result();
t1.get_stud_info();
t1.get_stud_marks();
t1.get_total_marks();
t1.disp_stud_info();
t1.disp_stud_marks();
t1.disp_total_marks();
}
}
/*
Enter Student Roll No:
1010
Enter Student Name:
James
Enter Student Test-1 Marks: 78
Enter Student Test-2 Marks:
90
*******STUDENT INFORMATION SYSTEM********
Student ROll No:1010
Student Name:James
Test-1 Marks:78
Test-2 Marks:90
Total Marks:168
*/
3) Hierarchical Inheritance:
- To create more than one derived class from only one base class is known as
Hierarchical inheritance.
- It is one of the types of inheritance.
- We use following syntax for creating the new class from old class.
- Program:
//Hierarchical Inheritance
import java.util.*;
class Student {
int rollno;
String name;
void get_stud_info() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno = sc.nextInt();
System.out.println("Enter Student Name:");
name = sc.next();
}
void disp_stud_info() {
System.out.println("Student Roll No: " + rollno);
System.out.println("Student Name: " + name);
}
}
void get_stud_marks() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1 = sc.nextInt();
System.out.println("Enter Student Test-2 Marks:");
marks2 = sc.nextInt();
}
void disp_stud_marks() {
System.out.println("Test-1 Marks: " + marks1);
System.out.println("Test-2 Marks: " + marks2);
}
}
void get_sport_info() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sport Weightage:");
sport_wt = sc.nextFloat();
}
void disp_sport_info() {
System.out.println("Sport Weightage: " + sport_wt);
}
}
class MethodOverridingDemo {
public static void main(String args[]) {
Derived d1 = new Derived();
d1.display(); // Calls overridden method
}
}
/*
display() method of Base class
display() method of Derived class
*/
====================================
How to invoke Base class Constructor
=====================================
- Base class constructor should not inherit in its sub class.
- Suppose, base class contain constructor then how we can call that
constructor.
- In this case, we can super keyword.
- super keyword should be the first line of derived class constructor body.
- Syntax-
super(); // Calls base class default constructor
OR
super(argument_list); // Calls base class parameterized constructor
- Program1:
class Base {
Base() {
System.out.println("Base class constructor called...!!!");
}
}
/*
Base class constructor called...!!!
Derived class constructor called...!!!
*/
-Program2:
//use of super keyword for calling base class parameterized constructor.
class Base {
int x;
Base(int m) {
x = m;
System.out.println("Base class constructor called.. m = " + m);
}
}
Derived(int p, int q) {
super(p); // Calling Base class constructor
y = q;
System.out.println("Derived class constructor called.. q = " + q);
}
}
class InvokeBaseClassConstructor1 {
public static void main(String args[]) {
Derived d1 = new Derived(100, 200);
}
}
/*
Base class constructor called..x=100
Derived class constructor called..y=200
*/
============
Final Keyword
============
- final is a predefined keyword.
- Following are the uses of final keyword:
---------------------
Final Variable
---------------------
1) To make constant variable:
- If we declare the variable using final keyword then that variable become
Constantin java.
- Constant variable means, once it is created then we cannot change its value
later.
- Constant us a variable which cannot change its value during the execution
of program.
- Example:
class finalKeywordDemo
{
public static void main(String args[])
{
final float PI=3.14f; //constant variable
int radius=2;
float area;
area=(PI*radius*radius);
System.out.println("Area of Circle="+area);
}
}
/*
Area of Circle=12.56
*/
---------------------
Final Method
---------------------
2) To avoid method overriding:
- Suppose, base class method name and derived class method name are same
then base class method overridden by derived class method.
- If we want to avoid method overriding then we can use final keyword
before the base class method declaration.
- Example:
//To avoid method overriding
class Base
{
final void display()
{
System.out.println("display method of base class");
}
}
class Derived extends Base
{
void display()
{
System.out.println("display method of derived class");
}
}
class AvoidMethodOverriding
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
}
}
/*
error: display() in Derived cannot override display() in Base
void display() {
^
overridden method is final
1 error*/
---------------------
Final Class
---------------------
3) To avoid inheritance:
- To avoid inheritance then we can declare the base class using final
keyword.
- If we declare base class using final keyword then we cannot create subclass
from it.
- Example: //To avoid method overriding final
class Base
{
void display()
{
System.out.println("display method of base class");
}
}
class Derived extends Base
{
void show()
{
System.out.println("show method of derived class");
}
}
class AvoidInheritance
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.show();
}
}
/*
AvoidInheritance.java:9: error: cannot inherit from final Base class Derived
extends Base */
Example
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();
// Regular method
void sleep() {
System.out.println("This animal is sleeping.");
}
}
class Main {
public static void main(String[] args) {
// Creating an object of the subclass
Dog myDog = new Dog();
Example:
interface Area
{
float PI=3.14f;
void compute(int x,int y);
}
The java compiler adds public and abstract keywords before the interface
method. It adds public, static and final keywords before data members.
Implementing interface:
• Class implements an interface.
• The class uses the implements keyword for implementing the interface.
• Class is responsible for implementing the abstract methods of the interface.
Syntax:
class class_name implements interface_name
{
//body of class
}
Example:
interface Area
{
float PI=3.14f;
void compute(int r);
}
class Circle implements Area
{
public void compute(int r)
{
System.out.println(“Area of Circle=”+(PI*r*r));
}
public static void main(String args[]) {
Circle c1=new Circle();
c1.compute(10);
}
}
Output:
Area of Circle=314.0
Extending interface:
• One interface can extend another interface same way that a class can extend
another class.
• The extends keyword is used to extend an interface.
• In this case sub interface inherits the properties of super interface, but it
will not define the methods of the super interface.
• Java class does not extend more than one class because java does not
support to the multiple inheritance.
• But interface is not a class, it can extend two or more interfaces, they are
separated by the commas.
Syntax:
interface sub_interface extends super_interface
{ //body of sub interface }
Example:
interface Abc
I {am from Abc interface:
void display();
I am from Xyz interface:
} interface Xyz extends Abc
{
void show();
}
class Mnp implements Xyz
{
public void display()
{
System.out.println(“I am from Abc interface:”);
}
public void show()
{
System.out.println(“I am from Xyz interface:”);
}
public static void main(String args[])
{
Mnp m1=new Mnp();
m1.display();
m1.show();
}
}
Output:
class extends class class implements interface interface extends interface interface extends class
Multiple inheritance in Java by using interface:
• To inherit the properties of more than one base class into sub class is known
as multiple inheritances.
• In multiple inheritance we can combine the features of more than one
existing class into new class.
• Below diagram shows the multiple inheritance concepts:
• Java classes cannot have more than one super class. But in most of the real
time application multiple inheritances is required. So java provides an
alternative approach is known as interface.
• Interface is a collection of static final variables and abstract methods. It is
used to achieve the multiple inheritance in Java.
• If a class implements multiple interfaces, or an interface extends multiple
interfaces i.e. known as multiple inheritance in Java.
1) Abstract class can have abstract and Interface can have only abstract methods.
nonabstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables. variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) Abstract class can extend another Java An interface can extend another Java
class and implements interface only.
multiple interfaces.
7) Abstract class achieves partial Interface achieves fully abstraction.
abstraction.
8) Example:
Example: interface Xyz
class Abc {
{ void draw();
Void draw(); }
}
Java Package:
• Putting classes and interfaces together is known as Package.
• Package is a collection of similar types of classes and interfaces.
• Packages are acts as container for the classes and interfaces.
• We can achieve the reusability features of Java by using Inheritance and
packages.
• Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces.
• A package is a collection of related classes. It helps Organize your classes
into a folder structure and make it easy to locate and use them. More
importantly, it helps improve re-usability.
• Each package in Java has its unique name and organizes its classes and
interfaces into a separate namespace, or name group.
• There are six main packages are present in Java programming language.
• Following table gives the information about the Java system packages
and their classes
Package Contents of the package
Name
In above example first_pkg is the package name and class Hello is added into it.
3. Create the subdirectory which has given the same name of package and
stored it into main directory where the source code is present.
4. Compile the source file, after that .class file stored into the subdirectory
which is created in step 3.
1) Using packagename.*;
• If you use package.* Statement then all the classes and interfaces of this
package will be accessible.
• import is a predefined keyword.
Syntax:
import Package_Name.*;
Example:
//Save by Abc.java
package first_pkg;
public class Abc
{
public void display()
{
System.out.println(“I am from Abc class:”);
}
}
//Save by Xyz.java
package
second_pkg;
import first_pkg.*;
class Xyz
{
public static void main(String args[])
{
Abc a1=new Abc(); a1.display();
}
}
Output:
I am from Abc class
2) import packagename.classname;
• If you use package.classname statement then only declared class of that
package will be accessible.
• import is a predefined keyword.
Syntax:
import Package_Name.classname;
Example:
//Save by Abc.java
package first_pkg;
public class Abc
{
public void display()
{
System.out.println(“I am from Abc class:”);
}
}//Save by Xyz.java
package
second_pkg;
import
first_pkg.Abc;
class Xyz
{
public static void main(String args[])
{
Abc a1=new Abc(); a1.display();
}
}
Output:
I am from Abc class
//Save by Abc.java
package first_pkg;
public class Abc
{
public void display()
{
System.out.println(“I am from Abc class:”);
}
}
//Save by Xyz.java
package
second_pkg;
class Xyz
{
public static void main(String args[])
{
first_pkg.Abc a1=new first_pkg.Abc (); //using fully qualified name
a1.display();
}
}
Output:
class StaticImportDemo
{
public static void main(String args[])
{
Advantage:
• Less coding is required if you have accessed any static member of a class.
Disadvantage:
• If you overuse the static import feature, it makes the program unreadable
and unmaintainable.
Package:
========
- Creating a package in java is quite easy.
- A package is always defined in a separate folder having the same name as a
package name.
- A package is a collection of related classes. It helps Organize your classes
into a folder structure and make it easy to locate and use them. More
importantly, it helps improve re-usability.
- Each package in Java has its unique name and organizes its classes and
interfaces into a separate namespace, or name group.
- The package must contain one or more classes or interfaces. This implies
that a package cannot be empty.
- The classes or interfaces that are in the package must have their source files
in the same directory structure as the name of the package.
- A package is always defined in a separate folder having the same name as a
package name.
- Define all classes in that package folder.
- All classes of the package which we wish to access outside the package
must be declared public.
- All classes within the package must have the package statement as its first
line.
- All classes of the package must be compiled before use (So that its error
free)
1) Write below line as first line of java source file package packageName;
2) Write java class which you want to add inside the package and make it as
public
3) Create directory whose name same as package name and stored java file
inside it and compile it.
4) Access created package in another program using below different ways
import packageName.*;
OR
import packageName.className;
Example: