0% found this document useful (0 votes)
8 views31 pages

OOPJ_4341602_Unit-3_2023 (1)

This document covers the concepts of inheritance, interfaces, and packages in Java, focusing on types of inheritance such as single, multilevel, hierarchical, and the limitations of multiple and hybrid inheritance. It explains method overriding, polymorphism, and the use of the 'super' and 'final' keywords, along with their implications in Java programming. Additionally, it discusses dynamic method dispatch, which is a runtime polymorphism mechanism in Java.

Uploaded by

krenishj
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)
8 views31 pages

OOPJ_4341602_Unit-3_2023 (1)

This document covers the concepts of inheritance, interfaces, and packages in Java, focusing on types of inheritance such as single, multilevel, hierarchical, and the limitations of multiple and hybrid inheritance. It explains method overriding, polymorphism, and the use of the 'super' and 'final' keywords, along with their implications in Java programming. Additionally, it discusses dynamic method dispatch, which is a runtime polymorphism mechanism in Java.

Uploaded by

krenishj
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/ 31

Object Oriented Programming with JAVA (4341602)| Unit-3

Unit - III: Inheritance, Interface and Package (CO2) (16 Marks)


 Define Inheritance. List out types of it. Explain multilevel and hierarchical inheritance with
suitable example. 07 – Summer-2023
 List out different types of inheritance. Explain multilevel inheritance. 04 – Winter-2023, 2024,
Summer-2024
Basics of Inheritance
 Inheritance is the process, by which class can acquire(reuse) the properties and methods of another
class.
 The mechanism of deriving a new class from an old class (existing class) is called inheritance.
 It is an important part of OOPS (Object Oriented programming system).
 A class that is inherited is called superclass (base/parent/old class). The class that does the inheriting is
called subclass (derived/child/new class).
 The derived class may have all the features of the base class and the programmer can add new features
to the derived class.

 Purpose of Inheritance
o To promote code reuse i.e. supporting reusability.
o To implement Polymorphism.
 In Java, “extends” key-word is used to inherit a class.
 Syntax of Java Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
 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.
 In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is
called child or subclass.
 All the properties of superclass except private properties can be inherit in its subclass using extends
keyword.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 1
Object Oriented Programming with JAVA (4341602)| Unit-3
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not supported in java through class)
5. Hybrid Inheritance (also known as Virtual Inheritance) (Not supported in java)
1. Single Inheritance
 If a class is derived from a single class, then it is called single inheritance.
 Class B is derived from class A
 Syntax:
class A //Parent Class A
{

}
class B extends A // Child Class B
{

}
Example,
class A {
void displayA() {
System.out.println("class A method");
}
}
class B extends A // Single Inheritance - class B is derived from class A
{
void displayB() {
System.out.println("class B method");
}
}
class InheritanceDemo {
public static void main(String[] args) {
B b = new B();
b.displayA();
b.displayB();
}
}
Output:
class A method
class B method
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 2
Object Oriented Programming with JAVA (4341602)| Unit-3
2. Multilevel Inheritance
 Any class is derived from a class which is derived from another class then it is called multilevel
inheritance.
 Here, class C is derived from class B and class B is derived from
 class A, so it is called multilevel inheritance.
 Syntax:
class A // A is parent class of B
{

}
class B extends A // B is child class of A
{

}
class C extends B // C is child class of B
{

}
Example,
class A {
void displayA() {
System.out.println("class A method");
}
}
class B extends A //Single Inheritance - class B is derived from class A
{
void displayB() {
System.out.println("class B method");
}
}
class C extends B // Multilevel Inheritance - class C is derived from class B
{
public void displayC() {
System.out.println("class C method");
}
}
class InheritanceDemo {
public static void main(String[] args) {
C c = new C();
c.displayA();
c.displayB();
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 3
Object Oriented Programming with JAVA (4341602)| Unit-3
c.displayC();
}
}
Output:
class A method
class B method
class C method

3. Hierarchical Inheritance
 If one or more classes are derived from one class, then it is called hierarchical inheritance.
 Here, class B, class C and class D are derived from class A.
 Syntax:
class A // A is parent class
{

}
class B extends A // B is child class of A
{

}
class C extends A // C is child class of A
{

}
Example,
class A {
void displayA() {
System.out.println("class A method");
}
}
class B extends A // Single Inheritance - class B is derived from class A
{
void displayB() {
System.out.println("class B method");
}
}
class C extends A // Hierarchical Inheritance - Class B and Class C are derived from Class A
{
public void displayC() {
System.out.println("class D method");

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 4


Object Oriented Programming with JAVA (4341602)| Unit-3
}
}
class InheritanceDemo {
public static void main(String[] args) {
B b = new B();
C c = new C();
b.displayA();
c.displayA();
}
}
Output:
class A method
class A method

4. Multiple Inheritance (Not supported in java through class)


 If a class is derived from more than one class, then it is called multiple inheritance.
 Here, class C is derived from two classes, class A and class B.
 It is not supported in java through class.
 Multiple inheritance is supported through interface only.

5. Hybrid Inheritance (also known as Virtual Inheritance) (Not supported in java)


 It is a combination of any other inheritance types that is either multiple or
multilevel or hierarchical or any other combination.
 Hybrid inheritance is combination of single and multiple inheritance.
 But java doesn't support multiple inheritance, so the hybrid inheritance is also
not possible.
 Hybrid inheritance is supported through interface only. We will learn about interfaces later.

 Define: Method Overriding. List out Rules for method overriding. Write a java program that
implements method overriding. 07 – Summer-2023, 2024, Winter-2024(04)
 Describe: Polymorphism. Explain run time polymorphism with suitable example in java. 07 –
Summer-2023
Method Overriding
 When a method in a subclass has the same name and type signature as method in its superclass, then
the method in the subclass is said to override the method of the superclass.
 Method overriding is used for runtime polymorphism.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 5


Object Oriented Programming with JAVA (4341602)| Unit-3
 Rules for method overriding:
o The overriding method must have same argument list as in the superclass.
o The overriding method must have same return type (or subtype) as in the superclass.
o A method declared final cannot be overridden.
o A method declared static cannot be overridden but can be re-declared.
o Only inherited methods can be overridden.
o Constructors cannot be overridden.
o Use the super keyword to invoke the overridden method from a subclass.
o Instance methods can be overridden only if they are inherited by the subclass.
o A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
o A subclass in a different package can only override the non-final methods declared public or
protected.
Example,
class DemoA {
public void display() // Parent Class - Overridden Method
{
System.out.println("Class A Method");
}
}
class OverridingDemo extends DemoA {
public void display() // Child Class - Overriding Method
{
System.out.println("Class B Method");
}
public static void main(String args[]) {
OverridingDemo obj1 = new OverridingDemo();
Obj1.display(); // method of class OverridingDemo invokes, instead of class A
}
}
Output:
Class B Method

Basics of Polymorphism
 Polymorphism in Java is a concept by which we can perform a single action in different ways.
 Polymorphism means “many forms”.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 6


Object Oriented Programming with JAVA (4341602)| Unit-3
 Two types of polymorphism in Java:
i. Compile-time polymorphism (Method Overloading)
ii. Runtime polymorphism (Method Overriding / Dynamic Method Dispatch)

 Difference between Method Overloading and Overriding


Sr.
Method Overloading Method Overriding
No
Overloaded methods MUST change the The argument list must exactly match that of the
1
argument list. overridden method.
Overloaded methods CAN change the return The return type must be the same as overridden
2
type. method in the super class.
While it is performed in two classes with
3 It is occur within the class.
inheritance relationship.
Method overloading may or may not require While method overriding always needs
4
inheritance. inheritance.
5 Private and final methods can be overloaded. Private and final methods cannot be overridden.
Static binding is being used for overloaded Dynamic binding is being used for overridden
6
methods. methods.
Method overloading is the example of compile Method overriding is the example of run time
7
time polymorphism. polymorphism.

 Advantages of Polymorphism
 Code Reusability: Polymorphism provides the reuse of code, as methods with the same name can be
used in different classes.
 Flexibility and Dynamism: Polymorphism allows for more flexible and dynamic code, where the
behavior of an object can change at runtime depending on the context in which it is being used.
 Reduced Complexity: It can reduce the complexity of code by allowing the use of the same method
name for related functionality, making the code easier to read and maintain.
 Simplified Coding: Polymorphism simplifies coding by reducing the number of methods and
constructors that need to be written.
 Better Organization: Polymorphism allows for better organization of code by grouping related
functionality in one class.
 Code Extensibility: Polymorphism enables code extensibility; as new subclasses can be created to
extend the functionality of the superclass without modifying the existing code.
 Increased Efficiency: Compile-time polymorphism can lead to more efficient coding. The compiler can
choose the appropriate method to call at compile time, based on the number, types, and order of
arguments passed to it.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 7


Object Oriented Programming with JAVA (4341602)| Unit-3
 Explain super keyword with example. 03 – Summer-2023, Winter-2023, 2024
super keyword
 The super keyword in java is a reference variable that is used to refer immediate parent class object.
 Usage of Java super Keyword:
 super can be used to refer immediate parent class instance variable.
o We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
 super can be used to invoke immediate parent class method.
o The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
 super() can be used to invoke immediate parent class constructor.
o The super keyword can also be used to invoke the parent class constructor.
Example,
class SuperA {
int a = 10;
SuperA() { // Default Constructor
System.out.println("Constructor of SuperA Class");
}
void show(int a) {
System.out.println("Class SuperA method");
}
}
class SuperB extends SuperA {
int a = 20;
SuperB() { // Default Constructor
super();
System.out.println("Constructor of SuperB Class");
}
void show(int a) { // Child Class - Overriding Method
super.show(a);
System.out.println("Class SuperB method");
System.out.println("Value of a (Local Variable): " + a);
System.out.println("Value of a (Instance Variable of Subclass): " + this.a);
System.out.println("Value of a (Instance Variable of Superclass): " + super.a);
}

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 8


Object Oriented Programming with JAVA (4341602)| Unit-3
}
class Exp17_SuperDemo {
public static void main(String args[]) {
SuperB b1 = new SuperB();
b1.show(30);
}
}
Output:
Constructor of SuperA Class
Constructor of SuperB Class
Class SuperA method
Class SuperB method
Value of a (Local Variable): 30
Value of a (Instance Variable of Subclass): 20
Value of a (Instance Variable of Superclass): 10

 Explain final keyword with example. 04 – Winter-2023, 2024, Summer-2023


final keyword
 The final keyword in java is used to restrict the user.
 The java final keyword can be used with: Variable, Method, Class
 Final Variable: If you make any variable as final, you cannot change the value of that final variable
(It will be constant).
o A variable that is declared as final and not initialized is called a blank final variable. A blank
final variable forces the constructors to initialize it.
 Final Method: Methods declared as final cannot be overridden.
 Final Class: Java classes declared as final cannot be extended means cannot inherit.
Example,
final class FinalA {
final int i = 1; //final variable must be initializing.
final void display() {
i=2; // Compile error – can’t change final variable value
System.out.println("Value of i is :: " + i);
}
}
class Exp13_FinalDemo extends FinalA { // Complie error - can't inherit final class
void display() // Compile error - final method can't override.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 9
Object Oriented Programming with JAVA (4341602)| Unit-3
{
System.out.println("Value of i is :: " + i);
}
public static void main(String args[]) {
Exp13_FinalDemo obj = new Exp13_FinalDemo();
obj.display();
}
}

 What is Dynamic Method Dispatch in Java? Explain with example. 04


Dynamic method dispatch
 Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time.
 It is also known as run-time polymorphism.
 Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
 When an overridden method is called through a superclass
reference, the determination of the method to be called is based on
the object being referred to by the reference variable.
 This determination is made at run time.
 A superclass reference variable can refer to a subclass object. It is known as Upcasting.
 Example,
class A{}
class B extends A{}
A a=new B(); // Upcasting
Example,
class DemoA {
public void display() // Parent Class - Overridden Method
{
System.out.println("Class A Method");
}
}
class DemoB extends DemoA {
public void display() // Child Class - Overriding Method
{
System.out.println("Class B Method");

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 10


Object Oriented Programming with JAVA (4341602)| Unit-3
}
}
class OverridingDemo extends DemoA {
public void display() // Child Class - Overriding Method
{
System.out.println("Class OverridingDemo Method");
}
public static void main(String args[]) {
DemoA a;
a = new OverridingDemo(); // Upcasting
a.display(); //At runtime, OverridingDemo’s display() is called
a = new DemoB(); // Upcasting
a.display(); //At runtime, DemoB’s display() is called
}
}
Output:
Class OverridingDemo Method
Class B Method

Object class
 The Object class is the parent class (java.lang.Object) of all the classes in java by default.
 Every class in java directly or indirectly derived from Object class.
 The Object class is beneficial if you want to refer any object whose type you don't know.
 Notice that parent class reference variable can refer the child class object, known as Upcasting.
 The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.
 Methods of Object class:
Method Description
public boolean equals(Object obj) Compares the given object to this object.
Returns a runtime representation of the class of this
public final Class getClass() object. By using this class object we can get information
about class such as its name, its superclass etc.
public String toString() Returns the string representation of this object.
public final void notify() Wakes up single thread, waiting on this object's monitor.
Wakes up all the threads, waiting on this object's
public final void notifyAll()
monitor.
Causes the current thread to wait for the specified
public final void wait(long timeout) throws
milliseconds, until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 11


Object Oriented Programming with JAVA (4341602)| Unit-3
public final void wait() throws Causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
Is invoked by the garbage collector before object is being
protected void finalize() throws Throwable
garbage collected.
Example,
class Student {
int id;
String name;
protected void finalize() {
System.out.println("Object cleaned");
}
}
public class ObjectClass {
public static void main(String[] args) {
Student obj1 = new Student();
obj1.id = 1;
obj1.name = "Rahul";
Student obj2 = new Student();
obj2 = obj1;
System.out.println(obj1); // Student@15db9742
System.out.println(obj1.toString()); // Student@15db9742
System.out.println(obj1.hashCode()); // 366712642
System.out.println(obj1.equals(obj2)); // true
System.out.println(obj1.getClass()); // class Student
System.out.println(obj1.getClass().getName()); // Student
obj1.finalize();
}
}
Output:
Student@15db9742
Student@15db9742
366712642
true
class Student
Student
Object cleaned

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 12


Object Oriented Programming with JAVA (4341602)| Unit-3
 Explain abstract class with suitable example. 07 – Summer-2023
Abstraction
 Abstraction is a process of hiding the implementation details and showing only functionality to the user.
 There are two ways to achieve abstraction in java
o Abstract class (0 to 100%)
o Interface (100%)
Abstract Class - A class that is declared with abstract keyword, is known as an abstract class in
java. It can have abstract and non-abstract methods (method with body).
 Features of Abstract Class:
o An instance of an abstract class cannot be created.
o If a class contains at least one abstract method then compulsory should declare a class as
abstract.
o It has non-abstract methods, constructors, static methods and member variables.
o It needs to be extended and its method implemented.
o If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method in child class or make this child class abstract.
o It can have a final method in abstract class but any abstract method in class (abstract class)
cannot be declared as final.
 Syntax:
abstract class class_name
{
//Number of abstract as well as non-abstract methods.
}
 Abstract method: A method that is declared as abstract and does not have implementation (body) is
known as abstract method.
 The method body will be defined by its subclass.
 If there is an abstract method in a class, that class must be abstract.
 Abstract method can never be final and static.
 Syntax:
abstract return_type function_name (); // No definition
Example,
abstract class vehicle {
public int noofwheel;
public vehicle() { // constructor

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 13


Object Oriented Programming with JAVA (4341602)| Unit-3
System.out.println("Vehicle Created");
}
void run() { // concrete method
System.out.println("Vehicle Running");
}
abstract void start();
abstract void stop();
}
class car extends vehicle {
void start() { // abstract method
noofwheel = 4;
System.out.println("Car started");
System.out.println("Car have " + noofwheel + " wheel.");
}
void stop() { // abstract method
System.out.println("Car stopped");
}
}
class bike extends vehicle {
void start() { // abstract method
noofwheel = 2;
System.out.println("Bike started");
System.out.println("Bike have " + noofwheel + " wheel.");
}
void stop() { // abstract method
System.out.println("Bike stopped");
}
}
class AbstractDemo {
public static void main(String[] args) {
car c = new car();
c.run(); Figure 1: Output
c.start();
c.stop();
bike b = new bike();

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 14


Object Oriented Programming with JAVA (4341602)| Unit-3
b.start();
b.stop();
}
}

 What is interface? Explain multiple inheritance with example. 07 - Winter-2023, 2024, Summer-
2024
 Describe: Interface. Write a java program using interface to demonstrate multiple inheritance. 07
- Summer-2023
Interface - An interface is a collection of abstract methods. An interface is not a class.
 When you create an interface it defines what a class can do without saying anything about how the
class will do it.
 It is used to achieve fully abstraction and multiple inheritance in Java.
 Rules for interface:
o Interface contains only static constants and abstract methods only.
o All variables declared inside interface are public, static and final variable by default
(Implicitly).
o All methods declared inside interface are public and abstract even if you don’t use.
o Interface can extend one or more other interface.
o Interface can’t implement a class.
 Similarity between class and interface are given below:
o An interface can contain any number of methods.
o An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
o The bytecode of an interface appears in a .class file.

Sr.
Class Interface
No.
1 Object of class can be created. Object of interface can’t be created.
2 It can contain constructors. It cannot contain constructors.
3 It cannot contain abstract methods. It contains abstract methods only.
4 Variables in a class can be static, final, or neither. All variables are static and final.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 15


Object Oriented Programming with JAVA (4341602)| Unit-3

5 Classes do not support multiple inheritance. The interface supports multiple inheritance.
It can be inherited by a class by using the
It can be inherited by another class using the
6 keyword ‘implements’ and it can be inherited by
keyword ‘extends’.
an interface using the keyword ‘extends’.

 Declaring Interfaces
 The interface keyword is used to declare an interface.
 Syntax: NameOfInterface.java
interface Interface_Name{
// Any number of final, static fields
// Any number of abstract method declarations
// Declare default method (optional)
// Declare static method (optional)
}
Example: DemoInterface.java
interface DemoInterface{
int i = 10; // complier take as public static final int i=10;
void demo(); // complier take as public abstract void demo();
}

 Implementing Interfaces
 A class uses the implements keyword to implement an interface.
 A class implements an interface means, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface.
 If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
 Syntax:
class classname implements interface_name
{
// Class-body (must implement or defines all abstract methods of the interface)
}
Example1,
interface InterfaceDemo {
int a = 10; // public, static and final variable
void display(); // public and abstract method
}
class InterfaceDemo1 implements InterfaceDemo {

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 16


Object Oriented Programming with JAVA (4341602)| Unit-3
public void display() {
System.out.println("InterfaceDemo1 called ");
}
public static void main(String args[]) {
InterfaceDemo1 obj = new InterfaceDemo1();
obj.display();
System.out.println("value of a: "+a);
}
}
Output:
InterfaceDemo1 called
value of a: 10
Example2,
interface Language { // create an interface
void getName(String name); // abstract method
}
class ProgrammingLanguage implements Language { // class implements interface
public void getName(String name) { // implementation of abstract method
System.out.println("Programming Language: " + name);
}
}
class InterfaceLang {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Java");
}
}
Output: Programming Language: Java

 Extending Interfaces
 We all knows a class can extend another class. Same way an interface can extend another interface.
 The extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.
Example,
interface InterfaceA {

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 17


Object Oriented Programming with JAVA (4341602)| Unit-3
void print(String msg);
}
interface InterfaceB extends InterfaceA {
void show();
}
class InterfaceExtend implements InterfaceB {
String m;
public void print(String msg) {
m = msg;
}
public void show() {
System.out.println(m);
}
public static void main(String args[]) {
InterfaceExtend obj = new InterfaceExtend();
obj.print("Welcome to Interface Extend");
obj.show();
}
}
Output: Welcome to Interface Extend

 Multiple Inheritance using Interface


 If a class implements multiple interfaces, or an interface extends multiple interfaces known as
multiple inheritance.
 A java class can only extend one parent class. Multiple inheritances are not allowed. However, an
interface can extend more than one parent interface.
 The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

Example,
interface Printable2 {

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 18


Object Oriented Programming with JAVA (4341602)| Unit-3
void print(String msg);
}
interface Showable2 {
void show();
}
class InterfaceMultiple implements Printable2, Showable2 {
String display;
public void print(String msg) {
display = msg;
}
public void show() {
System.out.println(display);
}
public static void main(String args[]) {
InterfaceMultiple obj = new InterfaceMultiple();
obj.print("Welcome to Interface Demo3");
obj.show();
}
}
Output: Welcome to Interface Demo3

Example, Hybrid Inheritance


interface Vehicle2 {
default void test() {
System.out.println("Testing a Vehicle");
}
}
interface Car extends Vehicle2 {
void start();
void enginecar();
}
interface Bike extends Vehicle2 {
void start();
void enginebike();
}

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 19


Object Oriented Programming with JAVA (4341602)| Unit-3
class MultipleInterface implements Car, Bike {
public void start() {
System.out.println("Vehicle started");
}
public void enginecar() {
System.out.println("Car engineer started");
}
public void enginebike() {
System.out.println("Bike engineer started");
}
public static void main(String[] args) {
MultipleInterface m = new MultipleInterface();
m.test();
m.start();
m.enginebike();
m.enginecar();
}
}
Output:
Testing a Vehicle
Vehicle started
Bike engineer started
Car engineer started

default method in Java


 Before Java 8, we could only declare abstract methods in an interface. However, Java 8 introduced the
concept of default methods.
 Java provides a facility to create default methods inside the interface.
 Methods which are defined inside the interface and tagged with default are known as default
methods. These methods are non-abstract methods.
Example,
interface VehicleDemo {
void cleanVehicle();
default void startVehicle() {
System.out.println("Vehicle is starting");

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 20


Object Oriented Programming with JAVA (4341602)| Unit-3
}
}
public class DefaultMethodDemo implements VehicleDemo {
public void cleanVehicle() {
System.out.println("Cleaning the vehicle");
}
public static void main(String args[]) {
DefaultMethodDemo car = new DefaultMethodDemo();
car.cleanVehicle();
car.startVehicle();
}
}
Output:
Cleaning the vehicle
Vehicle is starting

lambda expression
 Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides
a clear and concise way to represent one method interface using an expression. It is very useful in
collection library. It helps to iterate, filter and extract data from collection.
 The Lambda expression is used to provide the implementation of an interface which has functional
interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again
for providing the implementation. Here, we just write the implementation code.
 Java lambda expression is treated as a function, so compiler does not create .class file.
 Functional Interface - Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface.
 Why use Lambda Expression?
o To provide the implementation of Functional interface.
o Less coding.
 Lambda Expression Syntax: (argument-list) -> {body}
Example,
interface Interface1 {
public String print(String name);
}
public class LambdaExperssion {

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 21


Object Oriented Programming with JAVA (4341602)| Unit-3
public static void main(String[] args) {
Interface1 i = (name) -> {
return "College Name: "+name;
};
System.out.println(i.print("tdec"));
}
}
Output: College Name: tdec

 Difference Abstract classes v/s Interfaces


Sr.
Abstract class Interface
No
Abstract class can have abstract and non- Interface can have only abstract methods. Since
1
abstract methods. Java 8, it can have default and static methods also.
Abstract class doesn't support multiple
2 Interface supports multiple inheritance.
inheritance.
Abstract class can have final, non-final, static
3 Interface has only static and final variables.
and non-static variables.
Abstract class can provide the implementation Interface can't provide the implementation of
4
of interface. abstract class.
The abstract keyword is used to declare
5 The interface keyword is used to declare interface.
abstract class.
An abstract class can extend another Java class An interface can extend another Java interface
6
and implement multiple Java interfaces. only.
An abstract class can be extended using An interface can be implemented using keyword
7
keyword "extends". "implements".
A Java abstract class can have class members
8 Members of a Java interface are public by default.
like private, protected, etc.
Example: Example:
abstract class Shape{ interface Drawable{
9
abstract void draw(); void draw();
} }

 What is package? Write steps to create a package and give example of it. 07 - Winter-2023,
Winter-2024, Summer-2023(04), 2024
Package - Packages are similar to folders, which are mainly used to organize classes and interfaces.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 22
Object Oriented Programming with JAVA (4341602)| Unit-3
 A package is a group of similar types of classes, interfaces and sub-packages.
 Packages are used to prevent naming conflicts and provides access protection.
 We can also categorize the package by using concept of subpackage.
 Package inside the package is called the sub-package.
 Package can be categorized in two form:
i. Built-in packages (Pre-defined package): Existing Java package such as java.lang, java.util,
java.io, java.net, java.awt etc.

ii. User-defined-package: Java package created by user to categorized classes and interface
 Programmers can define their own packages to bundle group of classes, interfaces etc.

 Advantage of Java Package:


o Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
o Java package provides access protection.
o Java package prevent or removes naming conflict.
o Package provide reuse of the code (reusability).
o Repetition of code is minimized.

 Creating a package:
 Syntax:
package package_name;
//body
OR
package package_name.subpackage_name;
//body
 Note: The package statement should be the first line in the source file. There can be only one package statement in
each source file.
 If a package statement is not used then the class, interfaces etc. will be put into an unnamed package.
Example of Creating Package,
package com;

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 23


Object Oriented Programming with JAVA (4341602)| Unit-3
public class PackageDemo {
public static void main(String[] args) {
System.out.printl
n("Welcome to PackageDemo Class");
}
}
Output:
To Compile: D:\JAVA\Package> javac -d . PackageDemo.java
To Run: D:\JAVA\Package> java com.PackageDemo
Welcome to PackageDemo Class
Note:
o -d is a switch that tells the compiler where to put the class file (it represents destination).
o . (dot) represents the current folder/directory.

 Importing package, static import


 import keyword is used to import built-in and user-defined packages into your java source file.
 If a class wants to use another class in the same package, no need to import the package.
 But, if a class wants to use another class that is not exist in same package then import keyword is
used to import that package into your java source file.
 A class file can contain any number of import statements.
 There are three ways to access the package from outside the package:
1. import package.*;
2. import package.classname;
3. fully qualified name

1) By using packagename.* :
 If you use packagename.* then all the classes and interfaces of this package will be accessible but not
subpackages.
 Syntax: import packagename.*;
Example,
 Classone.java
package com;
public class Classone {
public void msg() {
System.out.println("Welcome to classone");

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 24


Object Oriented Programming with JAVA (4341602)| Unit-3
}
}
 Classtwo.java
package tdec;
import com.*;
public class Classtwo {
public static void main(String[] args) {
Classone obj=new Classone();
obj.msg();
}
}
Output:
To Compile:
D:\JAVA\Package>javac -d . Classone.java
D:\JAVA\Package>javac -d . Classtwo.java
To Run: D:\JAVA\Package>java tdec.Classtwo
Welcome to classone

2) By using packagename.classname
 If you use packagename.classname then only declared class of this package will be accessible.
 Syntax: import packagename.classname;
Example,
 Classone.java
package com;
public class Classone {
public void msg() {
System.out.println("Welcome to classone");
}
}
 Classtwo.java
package tdec;
import com.Classone;
public class Classtwo {
public static void main(String[] args) {
Classone obj=new Classone();

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 25


Object Oriented Programming with JAVA (4341602)| Unit-3
obj.msg();
}
}
Output:
To Compile:
D:\JAVA\Package>javac -d . Classone.java
D:\JAVA\Package>javac -d . Classtwo.java
To Run: D:\JAVA\Package>java tdec.Classtwo
Welcome to classone

3) By using fully qualified name


 If you use fully qualified name, then only declared class of this package will be accessible.
 No need to import the package.
 But you need to use fully qualified name every time when you are accessing the class or interface.
 This type of technique is generally used when two packages have the same class name example class
Date is present in both the packages java.util and java.sql.
Example,
 Classone.java
package com;
public class Classone {
public void msg() {
System.out.println("Welcome to classone");
}
}
 Classtwo.java
package tdec;
public class Classtwo {
public static void main(String[] args) {
com.Classone obj=new com.Classone(); // fully qualified name
obj.msg();
}
}
Output:
To Compile:
D:\JAVA\Package>javac -d . Classone.java
D:\JAVA\Package>javac -d . Classtwo.java

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 26


Object Oriented Programming with JAVA (4341602)| Unit-3
To Run: D:\JAVA\Package>java tdec.Classtwo
Welcome to classone

Static Import - The static import feature of Java 5 facilitates the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.
 Advantage of static import: Less coding is required if you have access any static member of a class
often.
 Disadvantage of static import: If you overuse the static import feature, it makes the program
unreadable and unmaintainable.
Example,
import static java.lang.System.*;
class StaticImportDemo{
public static void main(String args[]){
out.println("Hello"); //Now no need of System.out
out.println("Java");
}
}
Output:
Hello
Java

 Explain different access visibility controls used in Java. 04 – Summer-2023, Winter-2023, 2024
Access modifier, Access and class hiding rules in a package.
 Access modifiers is the process of controlling visibility of a variable or method.
 Access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
 There are four levels of visibility:
1. Private – Accessed only within class.
2. Public - Accessed from within class, outside class, within package and outside package.
3. Protected - Accessed only by classes that are subclass of class directly, Visible to package and all
sub Classes.
4. Default (or Package) - Visible to package. No modifiers are needed.
outside package by
Access Modifier within class within package outside package
subclass only
Private Y N N N
Default Y Y N N

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 27


Object Oriented Programming with JAVA (4341602)| Unit-3

Protected Y Y Y N
Public Y Y Y Y

1. Private access modifier


 The private access modifier is accessible only within the class.
 In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is a compile-
time error.
Example,
 AccessPrivateA.java
package p1;
class AccessPrivateA {
private String a = "TDEC";
private void show() {
System.out.println("Welcome to AccessPrivateA class");
}
}
 AccessPrivateB.java
package p1;
class AccessPrivateB {
public static void main(String[] args) {
AccessPrivateA obj=new AccessPrivateA();
System.out.println(obj.a); // Compile time error
obj.show(); // Compile time error
}
}
Output:
To Compile:
D:\JAVA\AccessModifier>javac -d . AccessPrivateA.java
D:\JAVA\AccessModifier>javac -d . AccessPrivateB.java
Error: AccessPrivateB.java:6: error: a has private access in AccessPrivateA
System.out.println(obj.a);
AccessPrivateB.java:7: error: show() has private access in AccessPrivateA
obj.show();

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 28


Object Oriented Programming with JAVA (4341602)| Unit-3
2. Default access modifier
 If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.
Example,
 AccessA.java (Inside p1 package)
package p1;
class AccessA {
void show() {
System.out.println("Welcome to classone");
}
}
 DemoB.java (Inside p1 package)
package p1;
class DemoB {
public static void main(String[] args) {
AccessA obj=new AccessA();
obj.show();
}
}
Output:
To Compile:
D:\JAVA\Package>javac -d . AccessA.java
D:\JAVA\Package>javac -d . DemoB.java
To Run: D:\JAVA\Package>java p1.DemoB
Welcome to AccessA class
 AccessB.java (Inside p2 package)
package p2;
import p1.*;
class AccessB {
public static void main(String[] args) {
AccessA obj=new AccessA(); // Compile time error
obj.show();
}
}

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 29


Object Oriented Programming with JAVA (4341602)| Unit-3
Output:
To Compile:
D:\JAVA\Package>javac -d . AccessA.java
D:\JAVA\Package>javac -d . AccessB.java
Error: AccessB.java:5: error: cannot find symbol
AccessA obj=new AccessA();
Note: AccessA class is default class, so it can’t be accessed from outside the package.

3. Protected access modifier


 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
Example,
 AccessProtectedA.java
package p1;
public class AccessProtectedA {
protected void show() {
System.out.println("Welcome to AccessProtectedA class");
}
}
 AccessProtectedB.java
package p2;
import p1.AccessProtectedA;
class AccessProtectedB extends AccessProtectedA {
public static void main(String[] args) {
AccessProtectedB obj = new AccessProtectedB();
obj.show();
}
}
Output:
To Compile:
D:\JAVA\AccessModifier>javac -d . AccessProtectedA.java
D:\JAVA\AccessModifier>javac -d . AccessProtectedB.java
To Run:

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 30


Object Oriented Programming with JAVA (4341602)| Unit-3
D:\JAVA\AccessModifier>java p2.AccessProtectedB
Welcome to AccessProtectedA class

4. Public access modifier


 The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example,
 AccessPublicA.java
package p1;
public class AccessPublicA {
public void show() {
System.out.println("Welcome to AccessPublicA class");
}
}
 AccessPublicB.java
package p2;
import p1.*;
class AccessPublicB {
public static void main(String[] args) {
AccessPublicA obj = new AccessPublicA();
obj.show();
}
}
}
Output:
To Compile:
D:\JAVA\Package>javac -d . AccessPublicA.java
D:\JAVA\Package>javac -d . AccessPublicB.java
To Run: D:\JAVA\Package>java p2.AccessPublicB
Welcome to AccessPublicA class

**********

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 31


inprotected.com

You might also like