Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module III Oops

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Module-3

• Interfaces -Interfaces - Interfaces vs. Abstract classes,


defining an interface, implementing interfaces - extending
interfaces.
• Packages
• Database Programming using JDBC Introduction to JDBC,
JDBC Drivers, JDBC connection.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Interfaces
• An Interface is a pure abstract class with only abstract methods and final variables.

Defining an Interface
interface inerfacename {
return-type method-name1(parameter-list);
type final-varname1 = value;
……
}
• The variable inside an interface are public, final and static, meaning they cannot be
changed by the implementing class. They must also be initialized.
• All methods are implicitly abstract and public.
Ex:
interface A{
int x=20;
void show();
}
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
Interfaces
Implementing Interfaces
• implements keyword is used to implement interface.
Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
• All the methods of an interface should be implemented in its sub class.
• If any method is not implemented in its subclass then declare that sub class as abstract
class.
• A sub class can implement more than one interface.
• We should not create an object for interface.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Interfaces

interface A
{ class demo3
int x=20; {
public void show(); public static void main(String[] args) {
} B ob=new B();
class B implements A ob.show();
{ }
int y=30; }
public void show()
{
system.out.println(x+y);
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Interfaces
John is a final year student of the SCOPE department at VIT-AP University. The placement season is on
and he will be sitting for the campus interviews. He and his friend Bob were brushing up their Java
concepts one day before the placements. Bob asked John to write a Java program that utilizes the
concept of an interface. John created an interface named Shape with two methods as depicted below:

• public double periTriangle ();. The method returns the perimeter of the triangle.

• public double periRectangle (); The method returns the perimeter of the rectangle.

•(NOTE: For calculating the perimeter of a triangle use the formula, perimeter = side1 + side2 + side3
and for calculating the perimeter of a rectangle use the formula perimeter = 2 * (side1 + side2)).
John attended Object Oriented Programming lectures at VIT-AP and created a class named Perimeter
that implements an interface Shape. In Perimeter class, declare 4 instance variables namely double
side1, double side2, double side3, and double perimeter and take the values of the variables double
side1, double side2, double side3 from the user. Create an object of the Perimeter class and access the
instance methods periTriangle and periRectangle and display the perimeters of triangle and rectangle.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Interfaces
import java.util.*;
interface Shape { class Demo5{
public double periTriangle(); public static void main(String[] args)
public double periRectangle(); {
} Scanner sc=new Scanner(System.in);
class Perimeter implements Shape { System.out.println("Enter 3 sides");
double side1, side2, side3,perimeter;
Perimeter(double s1,double s2,double s3) double s1=sc.nextDouble();
{ double s2=sc.nextDouble();
side1=s1; double s3=sc.nextDouble();
side2=s2;
side3=s3; Perimeter ob=new Perimeter(s1,s2,s3);
}
public double periTriangle() System.out.println("Perimeter of
{ Triangle is:"+ob.periTriangle());
perimeter=side1+side2+side3;
return perimeter; System.out.println("Perimeter of
} Rectangle is:"+ob.periRectangle());
public double periRectangle() }
{ }
perimeter=2*(side1+side2);
return perimeter;
} }
Implementing Multiple Inheritance
interface A
{
class Demo4
int x=20;
{
public void showA();
public static void main(String[] args)
}
{
C obj = new C();
interface B
obj.showA();
{
obj.showB();
int y=30;
}
public void showB();
}
}

class C implements A,B


{
public void showA()
{
System.out.println("X value is:"+x);
}
public void showB()
{
System.out.println("Y value is:"+y);
}
Extending Interfaces
• One interface can inherit another by use of keyword extends.

interface A class C implements B class demo6


{ { {
int x=20; public void showA() public static void main(String[] args) {
public void showA(); { C ob=new C();
} System.out.println("X is:"+x); ob.showA();
interface B extends A } ob.showB();
{ public void showB() }
int y=30; { }
public void showB(); System.out.println("Y is:"+y);
} }
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Default method in Interface
interface MyInterface { public class Default {
void abstractMethod(); public static void main(String[] args)
{
// Default method MyClass obj = new MyClass();
default void sample() {
System.out.println("This is a default method."); obj.sample();
} obj.abstractMethod();
} }
class MyClass implements MyInterface { }
public void abstractMethod() {
System.out.println("Abstract method
implementation.");
}
}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


PROBLEMS
1. Write a Java program to create an interface Shape with the
getArea() method. Create two classes Rectangle, Circle, that
implement the Shape interface.
Implement the getArea() method for each of the two classes.

2. Write a Java program to create an interface Resizable with


methods resizeWidth(int width) and resizeHeight(int height) that
allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize
methods

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Write a Java program to create an interface Shape with the getArea()
method. Create two classes Rectangle, Circle, that implement the Shape
interface. Implement the getArea() method for each of the two classes.

Shape interface
interface Shape { class Circle implements Shape {
double getArea(); double radius;
} public Circle(double radius) {
this.radius = radius;
class Rectangle implements Shape { }
double length; public double getArea() {
double width; return Math.PI * radius * radius;
public Rectangle(double length, double width) }
{ }
this.length = length;
this.width = width;
}
public double getArea() {
return length * width; public class Main {
} public static void main(String[] args) {
} Rectangle rectangle = new Rectangle(5, 3);
Circle circle = new Circle(4);
System.out.println("Rectangle area: " + rectangle.getArea())
System.out.println("Circle area: " + circle.getArea());
}}

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Write a Java program to create an interface Resizable with methods
resizeWidth(int width) and resizeHeight(int height) that allow an object to
be resized. Create a class Rectangle that implements the Resizable
interface and implements the resize methods.
public class Main { public static void main(String[]
interface Resizable { args)
void resizeWidth(int width); {
void resizeHeight(int height); Rectangle rectangle = new Rectangle(100, 150);
} rectangle.printSize();
rectangle.resizeWidth(150);
class Rectangle implements Resizable { rectangle.resizeHeight(200);
int width,height; rectangle.printSize();
public Rectangle(int width, int height) } }
{ this.width = width;
this.height = height;
}
public void resizeWidth(int width) {
this.width = width;
}
public void resizeHeight(int height) {
this.height = height;
}
public void printSize()
{ System.out.println("Width: " + width + ",
Height: " + height);
} }

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Packages
• A package represents a directory that contains related group of classes and interfaces.
• We use packages to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
Built-in Packages:
• These are the packages which are already available in Java language.
• These packages provide all most all necessary classes, interfaces and methods for the
programmer to perform any task in his programs
java . lang : String, Thread and basic classes
java. util: Scanner, Stack, LinkedList, Hashtable, Vector, Arrays, etc.

Importing packages:
• import java.util.Scanner; https://docs.oracle.com/javase/8/docs/api/.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


User-defined Packages
• The users of the Java language can also create their own packages. They are called user-
defined packages.
• User-defined packages can also be imported into other classes and used exactly in the
same way as the Built-in packages

Creating a Package:
package packagename;

Ex:
package myPackage;

• The preceding statements in fact create a directory with the given package name.
• We should of course add our classes and interfaces to this directory.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


User-defined Packages
package operations; import operations. Arithmetic;
public class Arithmetic class Example
{ {
public int add(int a,int b) public static void main(String arg[])
{ {
return a+b; Arithmetic ob=new Arithmetic();
} System.out.println(ob.add(5,6));
public int sub(int a,int b) System.out.println(ob.sub(5,6));
{ }}
return a-b;
} Execution:
} javac Example.java
java Example
O/P:
Compilation: 11
javac -d . Arithmetic.java -1
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE
• Create a package named prime.
• Inside the package, create a class named Primecheck with a method prime(n)
that checks whether a given number is prime or not.
• Create a separate Java program outside the package (e.g.,
calculate_prime.java) to use the Primecheck class to print the prime numbers
in the given list.
Primecheck.java calculate_prime,java

package prime;
import prime.Primecheck;
public class Primecheck {
public boolean prime(int n) { public class calculate_prime {
if (n <= 1) { public static void main(String[] args) {
return false; Primecheck pc= new Primecheck();
} int[] numbers = {2,3,4,5,6,7,8,9};
for (int i = 2; i <= n-1; i++) System.out.println("Prime numbers in
{ the given list:");
if (n % i == 0) { for (int num : numbers) {
return false; if (pc.prime(num)) {
} System.out.println(num);
} } } }}
return true;
} Prime numbers in the given list:
} 2 3 5 7
Define an interface Shape within the operations package. This
interface includes two constants, side1 and side2, and a method
periRectangle() intended to compute the perimeter of a rectangle.
Write a java class Perimeter outside of the operations package
which implements the Shape interface. Write a main() method
designed to showcase the functionality of the program.

Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE


Define an interface Shape within the operations package. This interface includes two constants,
side1 and side2, and a method periRectangle() intended to compute the perimeter of a rectangle.
Write a java class Perimeter outside of the operations package which implements the Shape
interface. Write a main() method designed to showcase the functionality of the program.

package operations; import operations. Shape;


interface Shape{ class Perimeter implements Shape {
double side1=5,side2=6; public double periRectangle()
{
public double periRectangle();
double perimeter=2*(side1+side2);
}
return perimeter;
} }
Compilation: class Example2{
javac -d . Shape.java public static void main(String[] args)
{
Execution:
javac Example2.java Perimeter ob=new Perimeter();
java Example2 System.out.println("ob.periRectangle())
O/P: 22 ;
Dr. Venkata Rami Reddy Ch , Sr. Assistant Professor, SCOPE } }
Define java abstract class Shape in package P1. Inherit two more classes:
Rectangle in package P2 and Circle in package P3. use constructor to read
the data and a method to display area. (Note: create a separate java file
outside those three packages, import all the three packages, define a class
called “Main” in which main() function should be present.
// File: Circle.java
// Shape.java package P3;
import P1.Shape;
package P1;
public class Circle extends Shape {
public abstract class Shape { private double radius;
public abstract double public Circle(double radius) {
calculateArea(); this.radius = radius;
} }
public double calculateArea() {
return Math.PI * radius * radius;
// Rectangle.java
}}
package P2;
import P1.Shape; // Main.java
public class Rectangle extends import P1.Shape;
Shape { import P2.Rectangle;
double length; import P3.Circle;
double width;
public Rectangle(double public class Main {
length, double width) { public static void main(String[] args) {
this.length = length; Rectangle r = new Rectangle(5, 4);
this.width = width; System.out.println("Area of Rectangle:"+
} r.calculateArea());
public double calculateArea() Circle c= new Circle(3);
{ System.out.println("Area of Circle:"+c.calculateArea());
return length * width; }}
Create a package named "traininformation" and another package named
"traininformation.users".
In the "traininformation" package, define a class named "Train" with properties such as TrainID,
Train name, date, starting point, and ending point.

In the "train information.users " package, define a class named "userinfo" with properties such
as user id, user name, user address, and user contact number.

Create a Java program to demonstrate the use of packages. In the main() method of this
program, create objects of the “Table” and "userinfo" classes.
// Train.java - Inside the traininformation package package traininformation.users;
public class UserInfo {
package traininformation; String userID;
String userName;
public class Train { String userAddress;
String trainID; String userContactNumber;
String trainName; public UserInfo(String userID, String userName, String userAddress, String
String date; userContactNumber) {
String startingPoint; this.userID = userID;
String endingPoint; this.userName = userName;
this.userAddress = userAddress;
public Train(String trainID, String trainName, String this.userContactNumber = userContactNumber;
date, String startingPoint, String endingPoint) { }
this.trainID = trainID; public void print()
this.trainName = trainName; {
this.date = date; System.out.println("User Information:");
this.startingPoint = startingPoint; System.out.println("User ID: " + userID);
this.endingPoint = endingPoint; System.out.println("User Name: " +userName);
} System.out.println("userAddress: " +userAddress);
public void print() System.out.println("userContactNumber: " +userContactNumber);
{ }
} import traininformation.Train;
System.out.println("Train Information:");
import traininformation.users.UserInfo;
System.out.println("Train ID: " + trainID);
public class TrainMain {
System.out.println("Train Name: " +trainName);
public static void main(String[] args) {
System.out.println("Date: " +date);
Train train = new Train("12345", "Express", "2024-05-10", "City A", "City B");
System.out.println("Starting Point: " +startingPoint);
train.print();
System.out.println("Ending Point: " +endingPoint);
UserInfo userInfo = new UserInfo("001", "John Doe", "123 Main St", "123-456-7890
}
userInfo.print();
}
}}
Define a class Test1 which contains public members as a and b in package
Pack1. Define another class Test2 which contains public members as c and d
in package Pack2. Create a separate java file to write a program outside
those packages to find out and print the highest number among a, b, c , d.
package Pack1; import Pack1.Test1;
import Pack2.Test2; public static int getMax(int
public class Test1
a,int b,int c,int d)
{ public class Main {
public int a; {
public static void main(String[] args)
public int b; int max = a;
{
} Test1 obj1 = new Test1(); if (b > max) {
obj1.a = 5; max = b;
obj1.b = 7; }
package Pack2; if (c > max) {
Test2 obj2 = new Test2(); max = c;
public class Test2 obj2.c = 10;
{
}
obj2.d = 8;
public int c; if (d > max) {
public int d; int max = getMax(obj1.a, obj1.b, max = d;
} obj2.c, obj2.d); }
System.out.println("The highest return max;
number among a, b, c, and d is: " + max); }
} }

You might also like