0% found this document useful (0 votes)
20 views136 pages

Y23 Aoop Co1&co2 - Notes

The document contains lecture notes on Advanced Object Oriented Programming (AOOP) covering key topics such as design patterns, clean coding techniques, test-driven development, generics, multi-threading, Java I/O, JDBC, servlets, and JSP. It includes a syllabus outlining the course objectives and various concepts along with short and long answer questions related to inheritance, abstract classes, interfaces, and design patterns. Additionally, it provides example programs illustrating these concepts in Java.

Uploaded by

panda.lazy53
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)
20 views136 pages

Y23 Aoop Co1&co2 - Notes

The document contains lecture notes on Advanced Object Oriented Programming (AOOP) covering key topics such as design patterns, clean coding techniques, test-driven development, generics, multi-threading, Java I/O, JDBC, servlets, and JSP. It includes a syllabus outlining the course objectives and various concepts along with short and long answer questions related to inheritance, abstract classes, interfaces, and design patterns. Additionally, it provides example programs illustrating these concepts in Java.

Uploaded by

panda.lazy53
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/ 136

Advanced Object Oriented Programming

( AOOP - R/A/E )

Lecture Notes

( quick preparation material - Y23 updated )

Prepared By

Dr MSR PRASAD
SEC-11 Adv
SYLLABUS

CO-1

1. Design Patterns

 Introduction to Design Patterns

 Creational Patterns

o Singleton, Factory Method, Abstract Factory

 Structural Patterns

o Decorator, Bridge, Adapter, Facade

 Behavioral Patterns

 Observer, Command, Iterator, Chain of Responsibility, Strategy, Template, Dependency Injection

2. Clean Coding Techniques

 SOLID Principles

 Code Smells

o Bloaters, Object-Oriented Abusers, Change Preventers, Dispensables, Couplers

 Refactoring Techniques

o Removing Code Smells

3. Test-Driven Development (TDD)

 Introduction to TDD, Unit Testing & JUnit5


CO-2

4. Generics & Collections Framework

 Introduction to Generics, Usage of Generics with Interfaces, Building Stacks, Queues, and
Priority Queues

 Comparator, Comparable, Cloneable & Iterator Interfaces

 Sets and Maps and Their Java API

 Functional Interfaces, Nested Classes, Lambda Expressions, and Stream API


CO-3

5. Multi-threading & Parallel Programming

 Introduction to Multithreading and Parallel Programming, Thread Concepts & States, Creating
Tasks & Threads, Thread Classes, Thread Pools, Thread Synchronization & Locks, Cooperation
Among Threads, Case Study: Producer/Consumer, Blocking Queues, Semaphores, Deadlock
Avoidance, Synchronized Collections & Parallel Programming

CO-4

6. Java I/O and JDBC

 Java I/O and Its Limitations

 JDBC: API, Components, Architecture (2-Tier & 3-Tier), Drivers & Their Types, Packages for JDBC
Connection, Steps to Connect to Databases (PostgreSQL)

7. Servlets

 Overview, Life Cycle of a Servlet, Attributes in Servlets, Interaction Between Client & Servlet,
Servlet Demo Application Development with Sessions

8. JavaServer Pages (JSP)

 Overview & Advantages Over Servlets, Features and Syntax, Life Cycle of JSP, Environmental
Setup for JSP, Interaction Between Client, JSP & Server, JSP Demo Application Development
CO - 1
SHORT ANSWER QUESTIONS ( from CO-1 )

1. Types of inheritance
Answer:
a) multilevel b) multiple c) Hierarchical d) hybrid inheritance

2. Multi level inheritance?


Answer:
class A , class B extends A , class C extends B is multilevel inheritance

3. Advantages of inheritance in java?


Answer:
1. Reusability 2. Better organization of the code 3. Clean coding technique 4.
Method overriding are the advantages.

4. Multiple inheritance in Java, what is the problem?


Answer:
Java supports single parent class to derive the child class, but multi inheritance
needs more than one super classes. To overcome this problem, the child class can
be derived from one class and one interface.

Eg: class Book extends Paper implements from Ink


Where
Paper is the super class
Ink is the interface.
5. Example of an abstract class
Answer:
abstract class AbsEmp {
abstract void show();
}

6. Example of abstract method in Java.


Answer:
abstract class AbsEmp {
abstract void show();
}
In this above program abstract method show() has no definition, it’s definition
must be overridden in the child class of the abstract class AbsEmp .

7. "implements" keyword in java


Answer:
“implements” keyword is used for interface .
Eg.
interface Iface {
void callMe();
}
Class Employee implements Iface {
Public void callMe() {
System.out.println(“ hello dude”);
}
}
8. “extends” keyword - in interfaces ?
Answer:
interfaces can be extended with keyword “extends”
Eg.
interface Iface1 {
void callMe();
}
interface Iface2 extends Iface1 {
void callMeToo();
}

9. Testing in software development - Explanation


Answer:
Coding and Testing are the important steps of software engineering. As per the
requirements project can be designed and developed (coded), after the coding part is
completed code should be tested for correctness of the results ie validation and
verification purposes.

10. Design patterns


Answer:
Design patterns represent the best practices used by experienced object-oriented
software developers. Design patterns are solutions to general problems that software
developers faced during software development. These solutions were obtained by
trial and error by numerous software developers over quite a substantial period of
time. Finally Design Patterns are a software engineering concept describing
recurring solutions to common problems in software design.
11. Uses of design patterns
Answer:
During the design phase of the software development design patterns are used. They
are programming language-independent strategies for solving a common problem.
That means a design pattern represents an idea, not a particular implementation. By
using design patterns, you can make your code more flexible, reusable, and
maintainable.

12. Uses of Singleton pattern.


Answer:
The Singleton pattern also supports lazy loaded and static initialization, helps in the
hiding of dependencies, and provides a single access point to a particular example.

13. List of creational design patterns?


Answer:
Singleton, Factory and abstract Factory design patterns

14. Uses of Structural Design patterns .


Answer:
In software engineering, structural design patterns are design patterns that ease the
design by identifying a simple way to realize relationships among entities.
Examples of Structural Patterns include: Adapter pattern: 'adapts' one interface for a
class into one that a client expects. Structural design patterns are blueprints for
combining objects and classes into larger structures to achieve multiple goals. They
simplify the structure by identifying relationships, such as how classes inherit from
each other and how they are composed from other classes.
15. What is the purpose and benefits of Observer Design Pattern?

Answer:

The observer design pattern is a behavioral design pattern that's useful when you
want to be notified of changes to an object's state. In this pattern, the object being
monitored is called the subject, and the object that monitors it is called the observer.

It supports the principle of loose coupling between objects that interact with each
other. It allows sending data to other objects effectively without any change in the
Subject or Observer classes. Observers can be added/removed at any point in time.

16. What is the purpose and benefits of Strategy Design Pattern?


Answer:

the strategy design pattern is a behavioral pattern that allows for the selection of an
algorithm during runtime. It provides flexibility and reusability by enabling the
calling code to choose from a set of algorithms instead of implementing a single
one.

It allows you to define a family of algorithms, encapsulate each one, and make them
interchangeable. It enables you to select and use an algorithm at runtime without
tightly coupling the client code to a specific implementation.

17. Phases of Test driven development


Answer:
1. Red Phase : planning and design stage i.e before coding
2. Green Phase : coding stage
3. Refactoring : code change
18. Refactoring of code
Answer:
To get the efficiency of the code, refactoring is required. In Refactoring the
behavior of the code is unchanged ie. Inputs is same and output is same. What
happens is the code is reorganized by changing data structures or input modes or
adding more functions or class hierarchical arrangements.

19. Characteristics of clean code


Answer:
The code that is easily readable, modifiable, testable, maintainable and is less prone
to errors is referred as "Clean Code".

20. Comments in clean coding


Answer:
Commenting is also considered as one of the best practises to make the code easily
understandable. In Java, two kinds of comments are allowed:

Documentation comments - The target audience is the users of codebase

Implementation comments - The target audience is the developers that work on the
codebase.

21. Variable - As per clean coding - Explanation


Answer:
A variable is considered as an identifier in programming languages,

Variables are used to represent data items in program. Variables are declared with
data types.

Eg . int marks;
boolean flag;

characters to declare a variable

a) length
b) begin with small letter or underscore
c) special characters used

22. Dead code / Lazy code


Answer:
Dead code is a code available in the program but has no significance, found no
references in the usage.

When there is no significance of a particular code segment, it is called dead code or


lazy code.

23. Relate a method call?


Answer:
In java methods are declared as class methods and instance methods.

Class methods: they are static methods called by its class or by any object.

Instance method : they are non static methods , called by only object of the class.

Eg.
Class Hamper{
Static void show(){
}
Void display(){
}
Public static void main(String[] args){
Hamper h1 = new Hamper();
Hamper. Show(); // static method call
h1.dispaly(); // non static method call
}
}
LONG ANSWER QUESTIONS ( from CO-1 )

1. Inheritance - Example program


Program:
class Animal {
void eat(){
System.out.println("Animals eat food");
}
void sleep(){
System.out.println("Animals sleep at night");
}
}

class Monkey extends Animal{


void jump(){
System.out.println("Monkeys easily jumps on trees");
}
void eat(){
System.out.println("Monkeys eat vegitarian food");
}
}
class Human extends Monkey{
void study(){
System.out.println("Humans study in great
universities");
}
void eat(){
System.out.println("Human eat cooked food and junk
food");
}
}

class DemoInh1{
public static void main(String[] args){
Animal aa = new Animal();
Human hh = new Human();
Monkey mm = new Monkey();
aa.eat();
aa.sleep();
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}

2. Inheritance – Example program -2 (method overriding)


(What is method overriding in java, Explain how runtime polymorphism is
achieved in java? Use at least two classes inheritance is the relationship between
them. Child class must override at least one method from the parent class.)

Answer:
Method Overriding: redefining a method from its super class. method overriding,
is an example of runtime polymorphism where as method over loading is the
example for compile time polymorphism.

Program:
class Monkey implements Animal{
public void eat(){
System.out.println("Monkeys eat vegitarian food");
}
public void sleep(){
System.out.println("Monkeys sleep on trees");
}
void jump(){
System.out.println("Monkeys jumps from tree to tree");
}
}

class Human extends Monkey{


@override from parent class
void eat(){
System.out.println("Human eat cooked food and junk
food");
}
void study(){
System.out.println("Humans study in great
universities");
}
}
class DemoInh1{
public static void main(String[] args){
Human hh = new Human();
Monkey mm = new Monkey();

mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}

3.Abstract class – Example program -1


(Java program to create abstract class Car, with abstract methods steering() and
braking(). Create a subclass Maruthi to implements abstract methods in it.)

Program:
abstract class Car {
abstract void steering();
abstract void breaking();
}
Class Maruthi extends Car{
@override
void steering(){
System.out.println(“ steering helps in turning the car
towards right and left”);
}
void breaking(){
System.out.println(“ breaks helps in slow down/stopping
the car”);
}
}

Class Demo{
Public static void main(String[] args){
Car c1 = new Maruthi();
c1. Steering();
c1.breaking();
}
}

4.Abstract class – Example program -2


(Java program with an abstract class Brazo in which callMe() method is an abstract
method. Write another java class that should implement callMe() method of Brazo
class, so that callMe() method can be called.)

Program:
abstract class Brazo {
abstract void callMe();
}
Class Carzo extends Brazo{
@override
void callMe(){
System.out.println(“ overriding callMe method from Brazo
calss”);
}
}
Class Demo{
Public static void main(String[] args){
Brazo b1 = new Carzo();
b1. callMe();
}
}

5. Interface –abstract class - Example program -1


(Java program interface Animal having atleast two methods in it, write a Monkey
class as abstract class, atleast one abstract method in it, Write Human class with
one method in it, test how the methods of Animal and Monkey are executed?)

Program:
interface Animal {
void eat();
void sleep();
}

abstract class Monkey implements Animal{


abstract void jump();
public void eat(){
System.out.println("Monkeys eat vegitarian food");
}
public void sleep(){
System.out.println("Monkeys sleep on trees");
}
}
class Human extends Monkey{
void study(){
System.out.println("Humans study in great
universities");
}
void eat(){
System.out.println("Human eat cooked food and junk
food");
}
}

class DemoInh1{
public static void main(String[] args){
Human hh = new Human();
Monkey mm = new Monkey();

mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
6. Interface - Example program -2
Answer:
overridden methods of interface are public only, demonstration of the statement is
the following statement.

Program :
interface One {
void callMe();
}

class IntImpl implements One {


public void callMe(){
System.out.println("callme: output");
}

void show(){
System.out.println(" Today is Sunny day ");
}
}

class DemoIntf1 {
public static void main(String[] args){
IntImpl if1 = new IntImpl();
if1.callMe();
if1.show();
}
}
7. Interface –Example program -3 ( Extends key word)
Answer:
Interfaces can be extended, as they follow inheritance of OOP concept.
Program :
interface One {
void callMe();
}
interface Two extends One {
void callMeToo();
}
// concrete class
class IntImpl implements Two {
public void callMe(){
System.out.println("callme: output");
}
public void callMeToo(){
System.out.println("callmeToo: output");
}
void show(){
System.out.println(" Today is wednesday");
}
}

class DemoIntf3 {
public static void main(String[] args){
IntImpl if1 = new IntImpl();
if1.callMe();
if1.callMeToo();
if1.show();
}
}

8. Multiple inheritance - Example program


Answer:
Java does not support multiple inheritance ie child class having two parent classes,
but it can be achieved through one parent as class and another as interface. The
following program demonstrates this feature.

Program :
interface One{
void callMe();
}

class Hello{
void greet(){
System.out.println("Hello world");
}
}

class HelloOne extends Hello implements One {


public void callMe(){
System.out.println("callme: output");
}
void show(){
System.out.println("today is wednes day");
}
}

class DemoIntf5{
public static void main(String[] args){
HelloOne ho1 = new HelloOne();
ho1.callMe();
ho1.greet();
ho1.show();
}
}

9. Differentiate interface with abstract class in java

Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.

5) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

10. Singleton design pattern – Example program


Answer;
Singleton pattern involves a single class which is responsible to create an object
while making sure that only single object gets created. This class provides a way to
access its only object which can be accessed directly without need to instantiate the
object of the class. It's useful when you need to control access to shared resources
or maintain a single point of control, such as in logging systems, database
connections, caches, and thread pools.

Important points:
1. Private default constructor
2. Static object
3. Static method to return the object to the caller.
4. Number of utility methods to be used by the object

Program :
class Hello{
private Hello(){
}
static Hello obj = new Hello();

static Hello getObject(){


return obj;
}

void show(){
System.out.println("Hello World");
}
}

class DemoSing1 {
public static void main(String[] args){

Hello h1 = Hello.getObject();
h1.show();
}
}

11. Factory design pattern Example Program-1 with Block diagram


Answer:
It's used when a superclass has multiple subclasses and the client program needs to
return one of the subclasses based on input. The pattern moves the responsibility of
instantiating a class from the client program to the factory class.

The pattern encapsulates object creation logic in a separate class, making the code
more flexible and maintainable. It also promotes loose coupling by eliminating the
need to bind application-specific classes into the code. This means the code only
interacts with the abstract class or resultant interface, so it can work with any
classes that extend or implement that interface.

Factory design pattern – bock diagram

Program:
import java.util.Scanner;
interface Shape{
void draw();
}

class Circle implements Shape{


public void draw(){
System.out.println(" circle has no sides");
}
}
class Square implements Shape{
public void draw(){
System.out.println(" square has all equal sides");
}
}

class Rectangle implements Shape{


public void draw(){
System.out.println(" rectangle has two sides equal");
}
}

class ShapeFactory {
Shape getShape(int x){
if (x==1)
return new Circle();
else if(x==2)
return new Square();
else if(x==3)
return new Rectangle();
else
return null;
}
}
class DemoFact1 {
public static void main(String[] args){
Shape sh;
int x;
ShapeFactory shft= new ShapeFactory();
Scanner in = new Scanner(System.in);
System.out.println("Enter 1/2/3 for circle/square/rect
:");
x=in.nextInt();
sh= shft.getShape(x);
sh.draw();
}
}

12. Factory design pattern - Example program – 2


Program:
import java.util.Scanner;
interface Service{
void loanPayment();
}

class SBI implements Service{


public void loanPayment() {
System.out.println(" Loan paid in SBI with roi 7.5%");
}
}
class HDFC implements Service{
public void loanPayment() {
System.out.println(" Loan paid in HDFC bank with roi
7.9%");
}
}

class ICICI implements Service{


public void loanPayment(){
System.out.println(" Loan paid in ICICI bank with roi
7.8%");
}
}

class BankFactory {
Service getService(int x){
if (x==1)
return new SBI();
else if(x==2)
return new HDFC();
else if(x==3)
return new ICICI();
else return null;
}
}
class FactoryDemo{
public static void main(String[] args){
Service sh;
int bank;
Scanner in = new Scanner(System.in);
System.out.println(" Enter 1/2/3 for SBI/HDFC/ICICI
banks”);
bank= in.nextInt();
BankFactory bf = new BankFactory();
sh= bf.getService(bank);
sh.loanPayment();
}
}

13. Abstract Factory design pattern program with Block Diagram


Answer:
The purpose of the Abstract Factory is to provide an interface for creating families
of related objects, without specifying concrete classes.

Factory Method Pattern allows the sub-classes to choose the type of objects to
create. It promotes the loose-coupling by eliminating the need to bind application-
specific classes into the code.
Abstract Factory design – block diagram

Program:
interface Shape{
void draw();
}

class Rectangle implements Shape{


public void draw(){
System.out.println(" I am a Rectangle");
}
}

class Square implements Shape{


public void draw(){
System.out.println(" I am a Square");
}
}

class RoundedRectangle implements Shape{


public void draw(){
System.out.println(" I am a rounded Rectangle");
}
}

class RoundedSquare implements Shape{


public void draw(){
System.out.println(" I am a rounded Square");
}
}

abstract class AbsFactory {


abstract Shape getShape(int x);
}

class ShapeFactory extends AbsFactory {


Shape getShape(int x){
if (x==1)
return new Rectangle();
else if(x==2)
return new Square();
else return null;
}
}

class RoundedShapeFactory extends AbsFactory {


Shape getShape(int x){
if (x==1)
return new RoundedRectangle();
else if(x==2)
return new RoundedSquare();
else return null;
}
}

class FactoryProducer{
static AbsFactory getFactory(int x){
if (x==1)
return new ShapeFactory();
else if (x==2)
return new RoundedShapeFactory();
else return null;
}
}

class AbsFactDemo1{
public static void main(String[] args){
AbsFactory abf;
Shape sh;
abf = FactoryProducer.getFactory(2);
sh= abf.getShape(2);
sh.draw();
}
}

14. Aggregation - Example program


Answer:
Aggregation is HAS-A type relation among java objects.
Class contains object of another class as it’s instance variable or as a local variable
so that all the members of the class can be accessed.

Program :
// Agrigation program – object as a instance variable (through constructor)

class Address {
String d_no;
String city;

Address( String d, String c){


d_no=d;
city=c;
}

void show_details(){
System.out.println("Door no -> "+d_no);
System.out.println("city -> "+ city);
}
}

class Employee {
String name;
String emp_no;
Address ad;

Employee( String n, String e, Address a){


name=n;
emp_no=e;
ad=a;
}

void show_details(){
ad.show_details();
System.out.println("name -> "+ name);
System.out.println("emp no -> "+emp_no);
}
}

class Aggregation1{
public static void main(String[] args){

Address aa= new Address("100", "Delhi");


Employee ee=new Employee("Rahul G", "CSE-255",aa);
ee.show_details();
}
}

15. Structural Design Patterns - Explanation


Answer:
There are many structural design patterns available, most popular among them are

1. Adopter design pattern


2. Bridge design pattern
3. Decorator design pattern
4. Façade design pattern

All of them use aggregation concept of oop.

Aggregation:

Aggregation is HAS-A type relation among java objects.

Class contains object of another class as it’s instance variable or as a local variable
so that all the members of the class can be accessed.

Advantages:

Structural patterns explain how to assemble objects and classes into larger
structures while keeping these structures flexible and efficient. These patterns help
make it easier to identify a simple way to realize relationships between entities.

The purpose of design patterns is simple - to provide structure. By giving you a


basic framework for problem-solving, they can speed up the development process.
Generally speaking, using design patterns will make your code more flexible,
reusable, and maintainable.

They are reusable in multiple projects.


They provide the solutions that help to define the system architecture.
They capture the software engineering experiences.
They provide transparency to the design of an application.

16. Adopter design pattern - Example program -1


Answer:
The adapter design pattern acts as a bridge between incompatible interfaces,
enabling them to collaborate without modifying their source code. It's a structural
design pattern that promotes code reusability and interoperability.

The following program demonstrates two incompatible interfaces, where CricPlayer


class and HockPlayer class are good to access their own methods. But

SpCrikPlayer class is acting like a connector to get methods from both of the
interfaces.

Program :
interface Cricket{
void playCricket();
}

interface Hockey{
void playHockey();
}
class CricPlayer implements Cricket{
public void playCricket(){
System.out.println(" playing cricket is my passion");
}
}

class HockPlayer implements Hockey{


public void playHockey(){
System.out.println(" playing hockey is my passion");
}
}

class SpCrikPlayer implements Cricket{


public void playCricket(){
Hockey hh = new HockPlayer();
hh.playHockey();
System.out.println(" playing cricket is my passion");
}
}

class AdoptDemo1 {
public static void main(String[] args){
Cricket ck, sck;
Hockey hk;
hk= new HockPlayer();
hk.playHockey();
ck = new CricPlayer();
sck = new SpCrikPlayer();
ck.playCricket();
sck.playCricket();
}
}

17. Adopter design pattern - Example program-2


Program:
interface Parrot{
void talk();
}

interface Duck{
void kwack();
}

class GreenParrot implements Parrot {


public void talk(){
System.out.println(" it talks good words");
}
}

class KDuck implements Duck {


public void kwack(){
System.out.println(" it makes sound kwack.. kwack");
}
}

class SpecDuck implements Duck{


Parrot p;
SpecDuck(Parrot pt){
p=pt;
}

public void kwack(){


System.out.println(" it makes sound kwack.. kwack");
p.talk();
}
}

class AdoptDemo2 {
public static void main(String[] raga){
Parrot p1;
Duck d1;

p1= new GreenParrot();


p1.talk();

d1= new KDuck();


d1.kwack();

d1= new SpecDuck(p1);


d1.kwack();
}
}
18. Decorator design pattern – Example program with Block Diagram
Answer:
The Decorator Design pattern extend the functionality of an existing object without
changing its code or breaking its clients. The decorator pattern also allows you to
compose different decorators at runtime, creating flexible and dynamic
combinations of behaviors.

Decorator design pattern - block diagram


Program:
interface Shape{
void draw();
}

class Circle implements Shape{


public void draw(){
System.out.println(" I am a circle");
}
}
class Rectangle implements Shape{
public void draw(){
System.out.println(" I am a rectangle");
}
}

class ShapeDecorator implements Shape{


Shape sh;
ShapeDecorator(Shape s){
sh=s;
}
public void draw(){
sh.draw();
System.out.println(" i have silver lining");
}
}

class RedShapeDecorator implements Shape{


Shape sh;
RedShapeDecorator(Shape s){
sh=s;
}
public void draw(){
sh.draw();
setRedBorder();
}
void setRedBorder(){
System.out.println(" i have red border");
}
}
class DecoDemo1{
public static void main(String[] args){
Shape s = new Circle();
Shape s1 = new ShapeDecorator(s);
RedShapeDecorator s2 = new RedShapeDecorator(s1);
s2.draw();

Shape s3 = new Rectangle();


Shape s4 = new ShapeDecorator(s3);
s4.draw();

}
}

19. Bridge design Pattern (Example-1)


Answer:
The Bridge design pattern separates an abstraction from its implementation,
allowing both to change independently. This structural pattern increases flexibility
and maintainability in complex systems.
Program:
interface Shape{
void show();
}

interface Deco{
void display();
}

class Circle implements Shape{


public void show(){
System.out.println(" i am a circle");
}
}

class Rectangle implements Shape{


public void show(){
System.out.println(" i am a Rectangle");
}
}

class Deco1 implements Deco{


Shape sh;
Deco1(Shape s1){
sh=s1;
}
public void display(){
sh.show();
System.out.println(" filled with Red color");
}
}

class Deco2 implements Deco{


Shape sh;
Deco2(Shape s1){
sh=s1;
}
public void display(){
sh.show();
System.out.println(" border color is blue");
}
}

class BridgeDemo1{
public static void main(String[] msr){
Shape sh;
Deco dc;
sh = new Rectangle();
dc = new Deco1(sh);
dc.display();
}
}
20. Bridge design Pattern (Example-2)
Answer:
The Bridge design pattern separates an abstraction from its implementation,
allowing both to change independently. This structural pattern increases flexibility
and maintainability in complex systems.

Program:
interface Bank{
void show();
}

interface Account{
void openAcc();
}

class SBI implements Bank{


Account ac;
SBI(Account ac1){
ac=ac1;
}
public void show(){
System.out.println(" welcome to SBI");
ac.openAcc();
}
}
class Axis implements Bank{
Account ac;
Axis(Account ac1){
ac=ac1;
}
public void show(){
System.out.println(" welcome to Axis Bank");
ac.openAcc();
}
}

class SavingAcc implements Account{


public void openAcc(){
System.out.println(" Your savings account opened successfully...");
}
}
class CurrentAcc implements Account{
public void openAcc(){
System.out.println(" Your current account opened successfully...");
}
}

class BridgeDemo2{
public static void main(String[] msr){
Bank bnk;
Account acc;
acc = new SavingAcc();
bnk = new Axis(acc);
bnk.show();

acc = new CurrentAcc();


bnk = new Axis(acc);
bnk.show();
}
}

21. Façade design pattern(Example-1)


Answer:
The Facade Design Pattern is a structural pattern that simplifies a system's interface,
making it easier to use and understand. It's often used for complex systems with
many classes or unavailable source code. The pattern provides a single interface
that hides the system's intricacies and shields clients from the implementation
details.

The Facade pattern offers the following benefits: It shields clients from subsystem
components, thereby reducing the number of objects that clients deal with and
making the subsystem easier to use. It promotes weak coupling between the
subsystem and its clients. Often the components in a subsystem are strongly
coupled.

Program:

// Facade design pattern is to hide the details of the subsystem...


interface Shape {

void draw();

class Rectangle implements Shape {

public void draw() {

System.out.println(" I am a Rectangle");

class Square implements Shape {

public void draw() {

System.out.println(" I am a square");

class Circle implements Shape {

public void draw() {

System.out.println(" I am a circle");

}
class ShapeMaker {

private Shape circle;

private Shape rectangle;

private Shape square;

public ShapeMaker() {

circle = new Circle();

rectangle = new Rectangle();

square = new Square();

void drawCircle(){

circle.draw();

void drawRectangle(){

rectangle.draw();

void drawSquare(){

square.draw();

}
class DemoFacadePattern1 {

public static void main(String[] args) {

ShapeMaker shapeMaker = new ShapeMaker();

shapeMaker.drawCircle();

shapeMaker.drawRectangle();

shapeMaker.drawSquare();

22. Façade Design Pattern (Example-2)


Program:
// This pattern is to hide the internal subsystem details to the user..

interface MobilePhone {
void modelNo();
void price();
}

class Iphone implements MobilePhone {

public void modelNo() {


System.out.println(" Iphone 6 ");
}
public void price() {
System.out.println(" Rs 65000.00 ");
}
}

class Samsung implements MobilePhone {


public void modelNo() {
System.out.println(" Samsung galaxy tab 3 ");
}

public void price() {


System.out.println(" Rs 45000.00 ");
}
}

class Blackberry implements MobilePhone {

public void modelNo() {


System.out.println(" Blackberry Z10 ");
}

public void price() {


System.out.println(" Rs 55000.00 ");
}
}
class ShopKeeper {
private MobilePhone iphone;
private MobilePhone samsung;
private MobilePhone blackberry;

ShopKeeper(){
iphone= new Iphone();
samsung=new Samsung();
blackberry=new Blackberry();
}
void iphoneSale(){
iphone.modelNo();
iphone.price();
}
void samsungSale(){
samsung.modelNo();
samsung.price();
}

void blackberrySale(){
blackberry.modelNo();
blackberry.price();
}
}
class DemoFacade2 {
public static void main(String args[]) {

ShopKeeper sk=new ShopKeeper();

sk.iphoneSale();
sk.samsungSale();
sk.blackberrySale();
}
}

23. Behavioral Design Patterns


Ans:
These design patterns are specifically concerned with communication between
objects.
1. Template DP
2. Iterator DP
3. Command DP
4. Chain of Responsibility
5. Dependency Injection

23. Template Pattern - Explanation


Answer:
Template pattern, This pattern comes under behavior pattern category. An abstract
class exposes defined way(s)/template(s) to execute its methods. Its subclasses can
override the method implementation as per need but the invocation is to be in the
same way as defined by an abstract class.
The Template Method design pattern allows subclasses to change the steps of an
algorithm without modifying its structure. This leads to more reusable and flexible
code. It's particularly beneficial when a part of an algorithm can vary, but the
structure of the algorithm is to be preserved.

Advantages:

1. Encourages Code Reusability: The Template Design Pattern promotes code


reuse by providing a common template or algorithm structure in the abstract
class.
2. Defines a Consistent Algorithm Structure: The pattern enforces a consistent
algorithm structure across multiple subclasses.
3. Easy to Use.
4. Time and Cost-efficient.
5. Proven through testing.

Model diagram:
24. Template design pattern for “making Tea” – Example program
Program:
abstract class Drink{
abstract void boilWater();
abstract void addTeaPowder();
abstract void addSugar();
abstract void serveTea();

final void makeTea(){


boilWater();
addTeaPowder();
addSugar();
serveTea();
}
}

class Tea extends Drink{


void boilWater(){
System.out.println(" boil water until we get fumes");
}

void addTeaPowder(){
System.out.println("add TEA powder and milk ");
}
void addSugar(){
System.out.println("add sugar as per your taste ");
}
void serveTea(){
System.out.println("Serve Tea in cups");
}
}

class TempDemo2{
public static void main(String[] args){
Drink gg;
gg= new Tea();
gg.makeTea();
}
}

25. Iterator design pattern - Explanation


Answer:
The iterator design pattern is a behavioral pattern that offers a sequential way to
access elements in an aggregate object without revealing its underlying structure.

The most important two methods are

1. public boolean hasNext();


2. public Object next();

hasNext() method will check whether next element is there in the list or not,
accordingly returns true if available otherwise returns false.

next() method will return the next element from the list if available.

Both these methods are made available through a interface, any class implementing
this interface can use both of these methods.
The implemented class must take care of objects of any type may be String or any
user defined type.

Example program can be written..

interface Iterator {
public boolean hasNext();
public Object next();
}

26. Iterator design pattern for “String objects” – Example program


Program:

interface Iterator {
Object next();
boolean hasNext();
}

class NameIterator implements Iterator{


String[] str = {"one","two","three","four","five"};
int index = 0;

public boolean hasNext(){


if (index < str.length)
return true;
else
return false;
}
public Object next(){
if(hasNext() == true)
return str[index++];
else
return null;
}
}

class IteratorDemo1{
public static void main(String[] msr){
NameIterator ni = new NameIterator();
while(ni.hasNext())
System.out.println((String) ni.next());
}
}

27. Iterator design pattern for Integer objects – Example program


Program:

interface Iterator {
Object next();
boolean hasNext();
}

class NumIterator implements Iterator{


int[] str = {30,35,40,45,50};
int index = 0;

public boolean hasNext(){


if (index < str.length)
return true;
else
return false;
}

public Object next(){


if(hasNext() == true)
return str[index++];
else
return null;
}
}

class IteratorDemo2{
public static void main(String[] msr){
NumIterator ni = new NumIterator();
while(ni.hasNext())
System.out.println((Integer) ni.next());
}
}
28. Command Design Pattern (Example program-1)
Answer:
The Command design pattern is a behavioral pattern that transforms a request into a
stand-alone object. It focuses on separating the sender of a request from the
receiver.

class WatchSon{
void bringVeg(){
System.out.println(" brought vegitables");
}
}

class WatchMan{
WatchSon ws;
WatchMan(WatchSon ws1){
ws = ws1;
}

void bringVeg(){
ws.bringVeg();
}
}

class Husband{
WatchMan wm;
Husband(WatchMan wm1){
wm = wm1;
}
void bringVeg(){
wm.bringVeg();
}
}

class CommandDemo1{
public static void main(String[] msr){
WatchSon w1 = new WatchSon();
WatchMan w2 = new WatchMan(w1);
Husband w3 = new Husband(w2);
w3.bringVeg();
}
}

29. Command Design Pattern (Example program-2)


Answer:
interface Bank{
void openAcc(int x);
}

class Account {
void savings(){
System.out.println(" your savings account opened");
}
void current(){
System.out.println(" your current account opened");
}
}

class SBI implements Bank{


Account ac;
SBI(Account ac1){
ac = ac1;
System.out.println(" welcome to SBI");
}

public void openAcc(int x){


if( x==1)
ac.savings();
else
ac.current();
}
}

class BankBazar{
Bank bk;
BankBazar( Bank bk1){
bk=bk1;
}
void service(int x){
bk.openAcc(x);
}
}

class CommandDemo2{
public static void main(String[] msr){
Account acc = new Account();
SBI sb = new SBI(acc);
BankBazar bz = new BankBazar(sb);
bz.service(2);
}
}

30. Dependency Injection Design Pattern ( program-1)


Answer:

Dependency injection (DI) is a design pattern that allows objects to receive


dependencies from an external source, instead of creating them internally. The main
purpose is to decouple objects from their dependencies, resulting in loosely coupled
classes. This makes code easier to maintain, read, and test.

Program-1:

interface Mobile{

void model();
void price();

class Iphone implements Mobile{

public void model(){

System.out.println(" model no = 15 pro max");

public void price(){

System.out.println(" this iphone mrp = Rs.1,40,000");

class Samsung implements Mobile{

public void model(){

System.out.println(" model no = fold 6");

public void price(){

System.out.println(" this phone mrp = Rs.1,30,000");

}
class SalesMan{

Mobile mb;

SalesMan(Mobile mb1){

mb=mb1;

void showDetails(){

mb.model();

mb.price();

class DepInj1{

public static void main(String[] args){

Mobile mb;

mb = new Samsung();

SalesMan sm = new SalesMan(mb);

sm.showDetails();

31. Dependency Injection Design Pattern ( program-1)

Program:

interface Shape{
void area(int x, int y);

class Triangle implements Shape{

public void area(int l, int b){

System.out.println(" Area of the triangle = "+ l*b/2);

class Rectangle implements Shape{

public void area(int l, int b){

System.out.println(" Area of the recangle = "+ l*b);

class ShapeMaker{

Shape sh;

ShapeMaker(Shape sh1){

sh = sh1;

}
void ShapeArea(int x, int y){

sh.area(x,y);

class DepInj2{

public static void main(String[] args){

//Shape ss = new Triangle();

Shape ss = new Rectangle();

ShapeMaker sm = new ShapeMaker(ss);

sm.ShapeArea(5,10);

32. What is the purpose and benefits of Chain of Responsibility Design


Pattern? (Program-1)
Answer:

The Chain of Responsibility (CoR) pattern in object-oriented design is a behavioral


pattern that passes requests through a chain of handlers until one handles
it. It's useful when you need to process different types of requests or change the
order of handlers at runtime.
The Chain of Responsibility pattern is a behavioral design pattern that allows you to
create a chain of loosely coupled objects that can handle a request. Each object in
the chain can either process the request or pass it to the next object.

Program:

import java.util.Scanner;

interface DChain{

void setNextChain(DChain dc);

void dispense(int x);

class L1Regd implements DChain{

DChain chain;

public void setNextChain(DChain dc){

chain = dc;

public void dispense(int x){

System.out.println("you registered for exams");

if (x>1) chain.dispense(x);

}
}

class L2Fee implements DChain{

DChain chain;

public void setNextChain(DChain dc){

chain = dc;

public void dispense(int x){

System.out.println("we received your fee");

if (x>2) chain.dispense(x);

class L3HallTkt implements DChain{

DChain chain;

public void setNextChain(DChain dc){

chain = dc;

public void dispense(int x){


System.out.println("you can download hall ticket");

class DemoChainExams{

public static void main(String[] msr){

DChain c1 = new L1Regd();

DChain c2 = new L2Fee();

DChain c3 = new L3HallTkt();

Scanner in = new Scanner(System.in);

int n;

c1.setNextChain(c2);

c2.setNextChain(c3);

System.out.println("Enter your choice 1/2/3");

n= in.nextInt();

c1.dispense(n);

33. Chain of Responsibility Design Pattern? (Program-2)


Program:

import java.util.Scanner;
interface DispenseChain {

void setNextChain(DispenseChain nextChain);

void dispense(int cur);

class Rs50Dispenser implements DispenseChain {

DispenseChain chain;

public void setNextChain(DispenseChain nextChain) {

chain=nextChain;

public void dispense(int cur) {

if(cur >= 50){

int num = cur/50;

int remainder = cur % 50;

System.out.println("Dispensing "+num+" X 50Rs. note");

if(remainder !=0) chain.dispense(remainder);

} else chain.dispense(cur);

}
class Rs20Dispenser implements DispenseChain{

DispenseChain chain;

public void setNextChain(DispenseChain nextChain) {

chain=nextChain;

public void dispense(int cur) {

if(cur >= 20){

int num = cur / 20;

int remainder = cur % 20;

System.out.println("Dispensing "+num+" X 20Rs. note");

if(remainder !=0) chain.dispense(remainder);

} else chain.dispense(cur);

class Rs10Dispenser implements DispenseChain {

DispenseChain chain;

public void setNextChain(DispenseChain nextChain) {


chain=nextChain;

public void dispense(int cur) {

if(cur >= 10){

int num = cur/10;

int remainder = cur % 10;

System.out.println("Dispensing "+num+" X 10Rs. note");

class DemoChainATM {

public static void main(String[] args) {

DispenseChain c1 = new Rs50Dispenser();

DispenseChain c2 = new Rs20Dispenser();

DispenseChain c3 = new Rs10Dispenser();

// set the chain of responsibility

c1.setNextChain(c2);

c2.setNextChain(c3);

while (true) {
int amount = 0;

System.out.println("Enter amount to dispense");

Scanner input = new Scanner(System.in);

amount = input.nextInt();

if (amount % 10 != 0) {

System.out.println("Amount should be in multiple of 10s.");

return;

// process the request

c1.dispense(amount);

34. Techniques / Characteristics of clean code.


Answer:
The code that is easily readable, modifiable, scalable(in some cases), maintainable
and is less prone to errors is referred as "Clean Code". Less prone to errors means
that there will be very less chances of getting bugs in that code.

Characteristics of Clean Code:

 Simple:

 Maintainable:

 Testable:
 Readable:

 Techniques of clean code:

1. All the resources must be placed in the respective folders for pro use and
maintenance
2. Proper Naming : all variables, constants, class names, method names,
Enum names must follow the conventions used in the industry
3. Anatomy of java program : as per the industry standards

4. White spaces and Indentation:


To increase the readability include white spaces wherever they are
appropriate. Indentation must be followed to understand the block of
statements ie group of logically related statements.
5. Method parameters : avoid too many parameters or arguments to be
passed in a method call, to achieve this think of data classes.
6. Hard coding : Data may be needed in different ways when project is
executed in real time, so while developing program use appropriate source
but always not from the key board.
7. Code comments : comments are required for every code component to
express its relevance in the project useful in the maintenance phase.
8. Log file : It is important to understand the execution of the code
9. SOLID properties : Simple , open/closed principle, Liskov substitution
principle, Interface segregation principle, Dependency inversion principle.
10. keep it simple and stupid whether it is design or code.
35. Clean coding techniques – Example program
Answer:
One important point in clean coding technique is to build a method with minimum
number of arguments.

a) Method parameters : avoid too many parameters or arguments to be passed in


a method call, to achieve this think of data classes.
b) Naming conventions
c) Comments :

I am going to illustrate a java program for the above concepts of clean coding,

Program:
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;
// constructor for data class
Address(int h, int r, String c){
house_no = h;
road_no = r;
city = c;
}
}
// main class
class StudentX{
// this method is getting more data from address object
void show(String name, Address ad1){
System.out.println( name );
System.out.println( ad1.house_no );
System.out.println( ad1.road_no );
System.out.println( ad1.city );
}

// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}

36. code smells - Explanation


Answer:
There are many known code smells that have been categorized as follows:

Bloaters: Bloaters are code, methods and classes that have increased to such
gargantuan proportions that they are hard to work with. Usually these smells do not
crop up right away, rather they accumulate over time as the program evolves (and
especially when nobody makes an effort to eradicate them). Long Method, Large
Class, Primitive Obsession, Long Parameter List and Data Clumps are famous in
this category.
Object-Orientation Abusers: All these smells are incomplete or incorrect application
of object-oriented programming principles. Switch Statements, Temporary Field,
Refused Request and Alternative Classes with Different Interface are known as
object-orientation abusers code smells.

Change Preventers: These smells mean that if you need to change something in one
place in your code, you have to make many changes in other places too. Program
development becomes much more complicated and expensive as a result. Code
smells like Divergent Change, Shotgun Surgery and Parallel Inheritance Hierarchies
are in this category.

Dispensable: A dispensable is something pointless and unneeded whose absence


would make the code cleaner, more efficient and easier to understand like
Comments, Duplicate Code, Lazy Class, Data Class, Dead Code and Speculative
Generality.

Couplers: All the smells in this group contribute to excessive coupling between
classes or show what happens if coupling is replaced by excessive delegation. Some
examples would be Feature Envy, Inappropriate Intimacy, Message Chains, Middle
Man and Incomplete Library Class

37. code smells within classes - Explanation


Answer:
Code Smells Within Classes
1. Comments: Yes, Comments are code smells too. It is like deodorant to the
code. If comments explain a few lines of complex code or a complex
expression, it should be made as a complete another function/ sub-expression
respectively.

2. Long Method: A long method contains too many lines of code. Any code
with more than 25 lines of code should make you question. It could be solved
using refactoring techniques like changing expression into sub-expression,
complex codes into a new function in order to make a function or method a
small and easy to read without changing its functionality.
3. Long Parameter List: Any function with more parameters is obviously more
complex. One of the thumb rules is to use a maximum of 3 to 4 parameters in
a function.
4. Large Classes: A class contains many methods/lines of code/fields is
considered a code smell. Refactoring techniques could be done like, extract
class, extract subclass, extract interface, duplicate observed data.
5. Duplicate Code: When a code is repeated for more than two times, merge it
into a function or a method of the class. If the same code is found in two or
more classes, using the extract method we can refactor the code smell.
6. Dead Code: The code that is not being used. A function with no calls or the
condition that never occurs. Delete unused code and unnecessary files.

38. code smells with in classes – Example Program


Answer:
One of the code smells within the class is
Long Parameter List: Any function with more parameters is obviously more
complex. One of the thumb rules is to use a maximum of 3 to 4 parameters in
a function.
I am going present a program to avoid above code smell.

Program:
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;

// constructor for data class


Address(int h, int r, String c){
house_no = h;
road_no = r;
city = c;
}
}

// main class
class StudentX{

// this method is getting more data from address object


void show(String name, Address ad1){
System.out.println( name );
System.out.println( ad1.house_no );
System.out.println( ad1.road_no );
System.out.println( ad1.city );
}

// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}

39. Demonstrate a code segment to represent duplicate.


Answer:
In the following code segment method1() and method2() methods are exactly the
same. This is an example of duplicate code.

public class MyClass {


public void method1() {
int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}

public void method2() {


int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}
}

40. Build a java program to remove duplicate code in Q.39


Answer :
By removing the duplicate code ie method2 from the above program, I am giving
the fully implemented program as follows.
class MyClass {
public void method1() {
int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}

public static void main(String[] args){


MyClass mc1 = new MyClass();
Mc1.method1();
}
}

41. Program on Liskov substitution principle (clean coding)


Program:

class Parent {
String name;
String ph;

Parent(){
}

Parent (String n1, String p1){


name = n1;
ph = p1;
}
void display(){
System.out.println(" name ="+ name);
System.out.println(" phone ="+ ph);
}
}

class Derived extends Parent{


String branch;
String clg;
Derived(String n1, String p1, String b1, String c1){
name=n1;
ph=p1;
branch = b1;
clg = c1;
}

void show(){
System.out.println(" name ="+ name);
System.out.println(" phone ="+ ph);
System.out.println(" branch ="+ branch);
System.out.println(" college ="+ clg);
}
}

class DemoLiskov{
public static void main(String[] args){
Parent obj = new Derived("Rahul","99999","CSE","KLEF");
// Liskov substitution goes here...
Derived doj = new Derived("Rani","88888","CSE","KLEF");
doj.show();
doj.display();
}
}
42. Dependency Inversion – program (clean coding)
Program:
class Parent {
Parent(){
}
void show(){
System.out.println("show method parent class");
}
}
class Derived extends Parent{
void show(){
System.out.println("show method child class");
}
void display(){
System.out.println("display method of child class");
}
}

class DemoDepInversion{
public static void main(String[] args){
//Parent obj = new Parent();
Derived obj = new Derived();
obj.show();
obj.display();
}
}

43. Interface segregation – program (clean coding)


Program:
interface Iface1{
void show();
}

interface Iface2 extends Iface1{


void display();
}

class One implements Iface2{


public void show(){
System.out.println("Show method of One class");
}

public void display(){


System.out.println(" display method of One class");
}

void hello(){
System.out.println(" Hello from one class");
}
}

class Two implements Iface1{


public void show(){
System.out.println("Show method of Two class");
}

void borrow(){
System.out.println(" borrow from Two class");
}
}

class InterfaceSegre{
public static void main(String[] args){
Iface1 oo;

oo = new One();
oo.show();

oo = new Two();
oo.show();
}
}
44. Usage of Data class – program ((clean coding)
Program:
class Data {
int x;
int y;
Data (int x1 , int y1){
x = x1;
y = y1;
}
}

class Compute{
Data dt;
Compute(Data dt1){
dt = dt1;
}

int sum(){
return dt.x + dt.y;
}
int subtract(){
return dt.x - dt.y;
}
}

class DataClass1{
public static void main(String[] msr){
Data dd = new Data(20,10);
Compute cp = new Compute(dd);
System.out.println("sum ="+ cp.sum());
System.out.println("difference ="+ cp.subtract());
}
}
45. Refactoring techniques - Example program.
Answer:
• Refactoring encompasses a number of specific code hygiene practices. When
it comes to eliminating code smells, however, there are three particularly
effective techniques: one that focuses on methods, another that focuses on the
method calls and a third that focuses on classes.

-------------------------------------
Program before refactoring:
-------------------------------------
class StudentY{
void show(String name, int house_no, int road_no, String
city){
System.out.println(name);
System.out.println(house_no);
System.out.println(road_no);
System.out.println(city);
}

public static void main(String[] args){


StudentY st1 = new StudentY();
st1.show("Rahul",100, 22, "vja");
}
}
-----------------------------------
Program after Refactoring:
-----------------------------------
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;
// constructor for data class
Address(int h, int r, String c){
house_no = h;
road_no = r;
city = c;
}
}

// main class
class StudentX{

// this method is getting more data from address object


void show(String name, Address ad1){
System.out.println( name );
System.out.println( ad1.house_no );
System.out.println( ad1.road_no );
System.out.println( ad1.city );
}

// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}

46. Extract Method - declare a method for reuse of code ( Refactoring )


Program:
class Employee{
int empId;
String empName;
int hno;
String city;
int pin;
Employee(int id, String en, int h, String c, int p){
empId =id;
empName =en;
hno=h;
city = c;
pin = p;
}
// normal way
void show(){
System.out.println(empId);
System.out.println(empName);
System.out.println(hno);
System.out.println(city);
System.out.println(pin);
}
// refactored way
void show(){
System.out.println(empId);
System.out.println(empName);
showAddress();
}

// method developed for refactoring...


void showAddress(){
System.out.println(hno);
System.out.println(city);
System.out.println(pin);
}
}
47. Replace Method with Method Object ( Refactoring )
Program:
class PrintHelloMethod {
String name;

PrintHelloMethod(String name) {
this.name = name;
}

// normal method
public void print() {
System.out.println("Hello, " + name);
}

// normal method from another class


public void printHello() {
PrintHelloMethod phm = new
PrintHelloMethod("World");
phm.print();
}
// refactored method
public void printHello() {
new PrintHelloMethod("World").print();
}

}
class Refactor2{
public static void main(String[] args){
PrintHelloMethod phm = new PrintHelloMethod("world");
phm.printHello();
}
}

48. Replace Temp with Query ( Refactoring )


Program:
public class Customer {
private double basePrice;

public double getDiscountedPrice() {


double discount = 0.1; // Normal way
double discountedPrice = basePrice * discount;
return discountedPrice;
}
}
public class Customer {
private double basePrice;
public double getDiscountedPrice() {
return basePrice * getDiscount(); //
Refactored way
}

private double getDiscount() {


return 0.1;
}
}
49. Hide Delegate – example ( Refactoring )
Program:
// Before refactoring
class MyClass {
MyDelegate delegate;
MyClass(MyDelegate delegate) {
this.delegate = delegate;
}
void doSomething() {
delegate.doSomething();
}
}

// After refactoring
interface MyDelegate {
void doSomething();
}
class MyClass {
MyDelegate delegate;
MyClass() {
this.delegate = new MyDelegate();
}
public void doSomething() {
delegate.doSomething();
}
}
50. Remove MiddleMan - java example ( Refacoring )
Program:
// Normal way...
class Boss1 {
private Worker w1;
Boss1( Worker ww){
w1 = ww;
}

public void doSomething() {


w1.doSomething() ;
}
}

class Worker{
void doSomething(){
System.out.println(" brought 1 kg chillies");
}
}

class Refactor5 {
public static void main(String[] args){
Worker w10 = new Worker();
Boss1 bb1 = new Boss1(w10);
bb1.doSomething();
}
}

// refactored way...
class Boss1 {
public void doSomething() {
System.out.println(" brought 1 kg chillies");
}
}

class Refactor51 {
public static void main(String[] args){
Boss1 bb1 = new Boss1();
bb1.doSomething();
}
}

51. Replace conditional with Polymorphism ( Refactoring )


Program:
// Before refactoring
class Bird {
private String type;
private int numberOfCoconuts;
private boolean isNailed;
private int voltage;

public String getSpeed() {


switch (type) {
case "EUROPEAN":
return "average";
case "AFRICAN":
return (numberOfCoconuts > 2) ? "tired" :
"average";
case "NORWEGIAN_BLUE":
return (isNailed) ? "0" : "beautiful";
default:
return "unknown";
}
}
}

// After refactoring
abstract class Bird {
private String type;

public Bird(String type) {


this.type = type;
}

public abstract String getSpeed();


}
class EuropeanSwallow extends Bird {
public EuropeanSwallow() {
super("EUROPEAN");
}

@Override
public String getSpeed() {
return "average";
}
}

class AfricanSwallow extends Bird {


private int numberOfCoconuts;

public AfricanSwallow(int numberOfCoconuts) {


super("AFRICAN");
this.numberOfCoconuts = numberOfCoconuts;
}

@Override
public String getSpeed() {
return (numberOfCoconuts > 2) ? "tired" : "average";
}
}
class NorwegianBlueParrot extends Bird {
private boolean isNailed;
private int voltage;

//Replace conditional with Polymorphism - example

public NorwegianBlueParrot(boolean isNailed, int


voltage) {
super("NORWEGIAN_BLUE");
this.isNailed = isNailed;
this.voltage = voltage;
}

@Override
public String getSpeed() {
return (isNailed) ? "0" : "beautiful";
}
}
// Usage example
Bird bird = new EuropeanSwallow();
System.out.println(bird.getSpeed()); // "average"

bird = new AfricanSwallow(3);


System.out.println(bird.getSpeed()); // "tired"
bird = new NorwegianBlueParrot(true, 110);
System.out.println(bird.getSpeed()); // "0"
CO - 2
SHORT ANSWER QUESTIONS ( from CO-2 )

1. Uses of Generics in Java?


Answer:
Java Generics allows us to create a single class, interface, and method that can be
used with different types of data (objects).

Generics does not work with primitive types (int, float, char, etc).

Code reusability is an advantage

2. Comparable interface - Explanation


Answer:
Java Comparable interface is used to order the objects of the user-defined class.
This interface is found in java.lang package and contains only one method named
compareTo(Object).

Syntax :

public int compareTo(Object obj): It is used to compare the current object with
the specified object. It returns

o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.

3. comparable and comparator interfaces - Differences.


Answer:
Comparable interface :
available in java.lang package
it’s method is compareTo( Object o1)
Comparator interface
available in java.util package
it’s method is compare( Object o1, Object o2)

4. HashSet – Explanation
Answer:
HashSet is commonly used if we have to access elements randomly. It is because

elements in a hash table are accessed using hash codes. The hashcode of an

element is a unique identity that helps to identify the element in a hash table.

HashSet cannot contain duplicate elements. Hence, each hash set element has a

unique hashcode.

Add(), remove(), size(), addAll(), retainAll(), removeAll(), clear() are the main

methods of the Hashset.

5. collection framework - Explanation


Answer:
Collection framework has three major interfaces List, Queue and Set

List has been implemented by arrayList, LinkedList and Vector classes

Queue is implemented by PriorityQueue class

Set is implemented by HashSet, LinkedHashSet and TreeSet

Collection framework classes are used to store and manage variety of Objects.
6. Map - Explanation
Answer:
Map interface is implemented by Hashmap, LinkedHashMap and TreeMap

A map contains values on the basis of key, i.e. key and value pair. Each key and
value pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a
key.

put(), remove(), getKey(), getValue(), entrySet() are the major methods of the Map.

7. iterator interface - Explanation


Answer:
Iterator interface provides the facility of iterating the elements in a forward
direction only, it is used along with many collection framework classes.

There are 3 methods in an iterator interface only.

Public Boolean hasNext() – returns true if element/s are available otherwise false.

Public Object next() – returns object if available

Public void remove() – last element returned by the iterator will be removed
LONG ANSWER QUESTIONS ( from CO-2 )

1. Generics / Generic method - Example program - 1


Answer:

Java Generics allows us to create a single class, interface, and method that can be
used with different types of data (objects).

Generics does not work with primitive types (int, float, char, etc).

Advantages:

1) Type-safety: We can hold only a single type of objects in generics. It doesn’t


allow to store other objects.
2) 2) Type casting is not required: There is no need to typecast the object.
3) 3) Compile-Time Checking: It is checked at compile time so problem will not
occur at runtime.
4) Code Reusability

Type Parameters :

The type parameters naming conventions are important to learn generics thoroughly.
The common type parameters are

1. T – Type 2. E – Element 3. K – Key 4. N – Number 5. V – Value

Program : whether the given number is Zero/Non-zero (Integer and Double types)

class Gen10{

<T> void check(T data1){

int i;
double d;

String s;

if(data1 instanceof Integer){

if( (Integer)data1 == 0)

System.out.println("ZERO");

else

System.out.println("non ZERO");

else if(data1 instanceof Double){

if( (Double)data1 == 0)

System.out.println("ZERO");

else

System.out.println("non ZERO");

public static void main(String[] args){

Gen10 g1 = new Gen10();

g1.<Integer>check(200);

g1.<Integer>check(0);

g1.<Double>check(12.6);

g1.<Double>check(0.0);

}
}

2. Generics class - Example program

Program: whether the given number is even/odd (Integer and Double types)

class Gen10 <T>{

T data1;

Gen10(T data1){

this.data1 = data1;

void check(){

int i;

double d;

String s;

if(data1 instanceof Integer){

if( (Integer)data1 == 0)

System.out.println("ZERO");

else

System.out.println("non ZERO");

else if(data1 instanceof Double){

if( (Double)data1 == 0)

System.out.println("ZERO");
else

System.out.println("non ZERO");

public static void main(String[] args){

Gen10<Integer> g1 = new Gen10<>(200);

g1.check();

Gen10<Integer> g2 = new Gen10<>(0);

g2.check();

Gen10<Double> g3 = new Gen10<>(200.99);

G3.check();

Gen10<Double> g4 = new Gen10<>(0.0);

g4.check();

3. Generic method - Example program- 2


Program: whether the given number is even/odd (Integer and Double types)

class Even {
<T> void checkOddEven (T number) {
if (number instanceof Integer) {
if ((Integer)number % 2 == 0)
System.out.println((Integer)number + "
is even number");
else
System.out.println((Integer)number + "
is odd number");

} else
if (number instanceof Double) {
if ((Double)number % 2 == 0)
System.out.println((Double)number + "
is even number");
else
System.out.println((Double)number + "
is odd number");
}
}
}
public class EvenDemo {
public static void main(String[] args) {
Even e = new Even();
e.<Integer>checkOddEven(11);
e.<Double> checkOddEven(13.0);
}
}

4 . Comparable interface – Example program.


Program: ( Find out the best object depends on cgpa of the student )
class Student implements Comparable<Student>{
String name;
int rank;
double cgpa;
double salarypak;

Student(String n, int r, double cg, double sp){


name=n;
rank=r;
cgpa=cg;
salarypak=sp;
}

public int compareTo(Student s){


if(cgpa > s.cgpa)
return 1;
else if(cgpa < s.cgpa)
return -1;
else return 0;
}
}

class CompDemo{
public static void main(String[] args){

Student s1 = new Student("Raman",100,9.9,12.5);


Student s2 = new Student("Kishore",40000,7.9,25.9);
int i = s1.compareTo(s2);
if(i==1)
System.out.println("Raman is best");
else if(i==-1)
System.out.println("Kishore is best");
else
System.out.println("Both are best");
}
}

5. comparable and comparator interfaces – Differences

Answer:

Comparable Comparator

1) Comparable provides compareTo() Comparator provides compare()


method to sort elements method to sort elements.

2) Comparable affects the original class, Comparator doesn't affect the original
i.e., the actual class is modified. class, i.e., the actual class is not
modified.

3). Comparable is present A Comparator is present in


in java.lang package. the java.util package.

4) Comparable provides a single sorting The Comparator provides multiple


sequence. sorting sequences.
5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by Collections.sort(List) method. by Collections.sort(List,
Comparator) method.

6. Clonable Interface

Method : public Object clone()

Program:
class Student implements Cloneable {
int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name;
}
@Override
Public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}

class ClonableInterface{
public static void main(String[] args) {
Student s = new Student(101, "Rahul");
System.out.println(s.id + " " + s.name);
try {
Student s1 = (Student) s.clone();
System.out.println(s1.id + " " + s1.name);
}catch (Exception e) {
System.out.println(e);
}
}
}

7. Block diagram of collection Framework


Answer:
8. ArrayList / LinkedList - Example Program-1 ( Integer objects )
Program:
import java.util.*;
class List1 {
public static void main(String[] args){
// create ArrayList or LinkedList as per the question
//LinkedList<Integer> numbers = new LinkedList<>();
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to ArrayList
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
System.out.println("ArrayList: " + numbers);
numbers.set(3,35);
System.out.println("size"+ numbers.size());
System.out.println(" ");
numbers.remove(3);
Iterator itr= numbers.iterator();
while(itr.hasNext()) {
System.out.print(itr.next());
System.out.print(" , ");
}
System.out.println("size"+ numbers.size());
}
}
9. ArrayList / LinkedList - Example Program-1 ( String objects )
Program:
import java.util.*;
class List2 {
public static void main(String[] args){

// create ArrayList or LinkedList as per the


question
//LinkedList<String> countries = new LinkedList<String>();
ArrayList< String > countries = new ArrayList< String >();
// Add elements to List
countries.add(“India”);
countries.add(“Australia”);
countries.add(“USA”);
countries.add(“Nepal”);
countries.add(“Russia”);
System.out.println("ArrayList: " + countries);

numbers.set(3,”Malaysia” );

System.out.println("size"+ countries.size());
System.out.println(" ");

countries.remove(2);
Iterator itr= countries.iterator();
while(itr.hasNext()) {
System.out.print(itr.next());
System.out.print(" , ");
}
System.out.println("size"+ countries.size());
}
}

10. Stack program


Program:

import java.util.Stack;
public class Stack1
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
System.out.println("top of the stack ="+ stk.pop());
}
}

11. Dequeue/ ArrayDequeue Program


Program:
import java.util.ArrayDeque;
import java.util.Deque;

public class DequeExample {


public static void main(String[] args) {
// Create a Deque using ArrayDeque
implementation
Deque<String> deque = new ArrayDeque<>();

// Add elements to the front


deque.addFirst("Element 1");
deque.offerFirst("Element 2");

// Add elements to the back


deque.addLast("Element 3");
deque.offerLast("Element 4");

// Print the Deque


System.out.println("Deque: " + deque);
// Remove elements from the front
String firstElement = deque.removeFirst();
System.out.println("Removed from front: " +
firstElement);

// Remove elements from the back


String lastElement = deque.removeLast();
System.out.println("Removed from back: " +
lastElement);

// Peek at the first element


String peekFirst = deque.peekFirst();
System.out.println("Peek first: " + peekFirst);

// Peek at the last element


String peekLast = deque.peekLast();
System.out.println("Peek last: " + peekLast);
}
}

12. Priority Queue – program


Program:
import java.util.PriorityQueue;

class PriorityQueue1 {
public static void main(String[] args) {
// Create a PriorityQueue using the natural
ordering (ascending)
PriorityQueue<Integer> pq = new
PriorityQueue<>();

// Add elements to the queue


pq.add(5);
pq.add(2);
pq.add(8);
pq.add(1);

// Print the queue (not necessarily in order)


System.out.println("PriorityQueue: " + pq);

// Remove and print elements in priority order


System.out.print("Elements in priority order:
");
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
}
}

13. HashSet / LinkedHashSet / TreeSet program with ( Integer Objects )


( Any four methods on Set )
Program:

import java.util.*;
class Set1 {
public static void main(String[] klu){

// declare set as per the question from the


following
// HashSet <Integer> list = new
HashSet<Integer>();
// LinkedHashSet <Integer> list = new
LinkedHashSet<Integer>();
TreeSet <Integer> list = new
TreeSet<Integer>();

// add() method ...


list.add(40);
list.add(20);
list.add(30);
list.add(70);
list.add(50);

System.out.println(list);

// contains() method ...


boolean x = list.contains(20);
System.out.println(x);
System.out.println(list.size());

// remove() method ...


list.remove(4);
System.out.println(list);
System.out.println(list.size());

// iterator() method ...


Iterator itr = list.iterator();
while(itr.hasNext()){
int i = (Integer) itr.next();
System.out.println(i);
}
}
}
14. HashSet / LinkedHashSet / TreeSet program with ( String Objects )
( Any four methods on Set )
Program:
import java.util.*;
class Set2 {
public static void main(String[] klu){

// declare set as per the question from the


following
TreeSet <String> list = new TreeSet<String>();
//LinkedHashSet <String> list = new LinkedHashSet<>();
//HashSet <String> list = new HashSet<String>();

// add() method ...


list.add("India");
list.add("canada");
list.add("Egypt");
list.add("Malaysia");
list.add("singapore");

System.out.println(list);

// contains() method ...


boolean x = list.contains("malaysia");
System.out.println(x);
System.out.println(list.size());

// remove() method ...


list.remove("Egypt");
System.out.println(list);
System.out.println(list.size());

// iterator() method ...


Iterator itr = list.iterator();
while(itr.hasNext()){
String i = (String) itr.next();
System.out.println(i);
}
}
}

15. HashSet / LinkedHashSet / TreeSet program ( Operations on Sets)


Answer:
Major Operations on Sets are performed with the following methods

1. Union - addAll() method


2. Intersection - retainAll() method
3. Difference - removeAll() method
Program:
import java.util.*;
class SetExample {
public static void main(String args[])
{
// declare set as per the question from the following
Set <Integer> list = new LinkedHashSet <>();

a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));

Set<Integer> b = new LinkedHashSet<Integer>();

b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
Set<Integer> union = new LinkedHashSet<>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);

Set<Integer> intersection = new HashSet<>(a);


intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);

Set<Integer> difference = new TreeSet<>(a);


difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}
16. Block diagram of Map interface and Explanation
Answer:

Map in Java is an interface available in java. util package and it stores the data in
key and value pairs. It does not allow duplicate keys.

TreeMap, HashMap and LinkedHashMap are the classes that are implementing
Map interface.

SortedMap is another interface extending Map.

TreeMap class implements both SortedMap and Map interfaces

The map() operation in Java 8 streams transforms the elements of a collection based
on a specified function. It takes a Function<T, R> as input, where T is the type of
the input element and R is the type of the output element.

Operations using Map Interface and HashMap/ LinkedHashMap /TreeMap


Adding Elements :
hm1.put(1, "Geeks");
hm2.put(new Integer(1), "Geeks");

Changing Element:
hm1.put(new Integer(2), "For");

Removing Elements:
hm1.remove(new Integer(4));

Iterating through the Map:


for (Map.Entry<String, Integer> e : map.entrySet())
System.out.println(e.getKey() + " "+
e.getValue());

By using the for-each loop, we get an entrySet() which provides an automated


“view” of the data in the map, in the form of key-value pairs. Each entrySet
contains a key and corresponding values.

17. HashMap/TreeMap/LinkedHashMap program with ( Integer Objects )


( Any Five methods of Map)
Program:
import java.util.*;
class MapDemo11{
public static void main(String[] args){
// use the following map declaration as per the question
//Map<String,Integer> mp = new HashMap<>();
//Map<String,Integer> mp = new LinkedHashMap<>();
Map<String,Integer> mp = new TreeMap<>();
// load elements
mp.put("one", 181);
mp.put("two", 275 );
mp.put("three",356);
mp.put("four", 499);
mp.put("five", 598);
System.out.println(" No of element in the map (before) :"+mp.size());

// removing an element
mp.remove("four");

// getting element from map


int str =(Integer) mp.get("five");
System.out.println(str);

// checking the size of the map


System.out.println(" No of element in the map (after) :"+mp.size());

// traversing through map (entrySet() method)


for(Map.Entry<String,Integer> myMap: mp.entrySet())
{
System.out.print(myMap.getKey()+" : ");
System.out.println(myMap.getValue());
}
}
}

18. HashMap/ LinkedHashMap /TreeMap program with ( String Objects )


( Any Five methods of Map )
Program:
import java.util.*;
class MapDemo1{
public static void main(String[] args){
// use the following map declaration as per the question

//Map<Integer,String> mp = new HashMap<>();


//Map<Integer,String> mp = new LinkedHashMap<>();
Map<Integer,String> mp = new TreeMap<>();

// load elements
mp.put(5,"India");
mp.put(2,"Srilanka");
mp.put(3,"USA");
mp.put(4,"Russia");
mp.put(1,"China");
System.out.println(" No of element in the map (before) :"+mp.size());

// removing an element
mp.remove(4);

// getting element from map


String str =(String) mp.get(5);
System.out.println(str);

// checking the size of the map


System.out.println(" No of element in the map (after) :"+mp.size());
// traversing through map (entrySet() method)
for(Map.Entry<Integer,String> myMap: mp.entrySet())
{
System.out.print(myMap.getKey()+" : ");
System.out.println(myMap.getValue());
}
}
}
19. Functional Interfaces and Lambda Expression
Answer:
A functional interface is an interface that contains only one abstract method. They
can have only one functionality to exhibit, it works for Abstract classes and
Interfaces.
Lambda Expression is used along with functional expression without any method
name, it works for only interfaces.
Variations in using Functional interfaces are shown in the following programs.
Program: ( Ordinary program without any Functional Interface)

interface Eatable{
void eat();
}

class One implements Eatable{


public void eat(){
System.out.println(" eating .. fruits");
System.out.println(" eating .. sweets");
}
}
class NoFuncInterface{
public static void main(String[] args){
Eatable eb = new One();
eb.eat();
}
}
Program 2: ( Method developed with its name -pure functional interface)
@FunctionalInterface
interface Eatable{
void eat();
}

class FuncInterface1 {
public static void main(String[] args){
Eatable eb = new Eatable(){
public void eat(){
System.out.println(" eating .. fruits");
System.out.println(" eating .. sweets");
}
};
eb.eat();
}
}

Program 3: ( Lambda expression without arguments )


@FunctionalInterface
interface Eatable{
void eat();
}
class Lamba1 {
public static void main(String[] args){
Eatable eb =()->{
System.out.println(" eating .. fruits");
System.out.println(" eating .. sweets");
};
eb.eat();
}
}

Program 4: ( Lambda Expression with two arguments )


@FunctionalInterface
interface Eatable{
void eat(String x, String y);
}

class Lamba2 {
public static void main(String[] args){
Eatable eb =(String a, String b)->{
System.out.println(" eating .. "+a);
System.out.println(" eating .. "+b);
};
eb.eat("fruits","sweets");
}
}
20. Nested classes

a) Inner class : The purpose of nested classes is to group classes that belong
together, which makes your code more readable and maintainable.

Program 1: ( Demo of Inner class )

class Outer
{
int outer_x=100;
void test()
{
Inner inner = new Inner();
inner.display();
inner.showy();
}

class Inner
{
int y=10;
void display()
{
System.out.println("dispaly: outer_x =" + outer_x);
}

void showy()
{
System.out.println(y);
}
}
}

class InnerClass
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}

b) Local class : A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block. Generally, this block is a
method body.

Program 1:

class JLInner1{
private int data=30;
void display(){
class Local{
void msg(){
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
JLInner1 obj=new JLInner1();
obj.display();
}
}

Program 2:
class JLInner2{
private int data=30;//instance variable
void display(){
int value=50;
class Local{
void msg(){
System.out.println("local variable: "+value);
System.out.println("instance variable: "+data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
JLInner2 obj=new JLInner2();
obj.display();
}
}

c) Anonymous class : a class that has no name is known as an anonymous inner class in Java.
It should be used if you have to override a method of class or interface.

Program 1:
abstract class Person{
abstract void eat();
}
class JAInner1{
public static void main(String args[]){
Person p=new Person(){
void eat(){
System.out.println("nice fruits");
}
};
p.eat();
}
}

Program 2:
interface Eatable{
void eat();
}
class JAInner2{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){
System.out.println("nice fruits");
}
};
e.eat();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy