Uploaded by Dummy Hacker

S10-S3-CTOOD2-CO3-converted (1)

advertisement
Abstract classes, Abstract methods
Final keyword for methods and classes
Template pattern, Introduction to interfaces, Interfaces vs
implementation,
Factory classes, factory method pattern
3
Generic classes, application of interfaces to build abstract
data structures,
Java API for Vector and LinkedList
comparable, comparator and cloneable,iterator interfaces.
Anonymous classes, Decorator pattern.
Event driven programming with event listeners
Introduction to Exceptions & Errors
Java API for exceptions
try, catch, finally
throw and throws keywords
4
try with resources, user defined exceptions
File IO, byte streams, character streams,
wrapper classes for Object IO using serializable.
String based algorithms using StringBuffer, String Builder,
String constant pool, regex, garbage collection.
NOTE:
ONLY Programs and Syntax are available here what we
discussed in class.Detail Explaination verify ur notes once
GUI please refer to class notes
Abstraction in JAVA
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way,it shows only essential things to the user and hides the internal details,for example
sendingSMS where you type the text and send the message,you don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it work.
Ways to achieve abstraction
abstract classes,methods
0 to 100
Interfaces
100
Abstract Class in Java
A class which is declared as abstract is known as an abstract class.It can have abstract and nonabstract methods.
It needs to be extended and its methods implemented.It cannot be instantiated.
Points to Remember
An Abstract class must be decalred with an abstract keyword
It can have abstract and non-abstract methods.
It cannot be instantiated
It can have constructors and static methods also.
It can have final methods which will force.
It can have final methods which will force the subclass not to change the
body of the methods.
Syntax for abstract class
abstract classes are declared by using abstract keyword
abstract classname{
}
Syntax for abstract methods
abstract returntype methodname() {
{
ex:
}
}
represents no body for the method.
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
Here run() is an abstract method, and
it is declared in Bike Class.
As Bike class contains one abstract
method so the Bike class is declared as
{
void run()
abstract.
{
System.out.println("Running Safely");
}
}
class DemoAbstract
Honda class which extends Bike
class,defines the run() method.
{
public static void main(String args[])
{
Honda h=new Honda();
h.run();
}
}
Example 1
Example 2
Classes having constructors,ordinary methods
Define a class shape as abstract and its implementation is provided by
the rectangle and circle classes.
and abstract methods.
abstract class Bike
abstract class Shape
{
{
Bike()
abstract void draw();
{
}
System.out.println("Bike Created");
class Rectangle extends Shape
}
{
void changeGear()
void draw()
{
{
System.out.println("Gear changed");
System.out.println("drawing rectangle");
}
}
void run(){
}
}
}
class Circle extends Shape
class Honda extends Bike
{
{
void draw()
void run()
{
{
System.out.println("drawing rectangle");
System.out.println("Running Safely");
}
}
}
}
class TestAbstract
public class TestAbstract1
{
{
public static void main(String args[])
public static void main(String args[])
{
{
Rectangle r=new Rectangle();
Honda h=new Honda();
r.draw();
h.run();
h.changeGear();
Circle c=new Circle();
c.draw();
}
}
}
}
Example 4
package abstractexample;
Example 3
abstract class Sum
{
abstract class MyTest
{
abstract void calculate(int a, int b); // No body.
public abstract int sumOfTwo(int a,int b);
}
public abstract int sumOfThree(int a,int b,int c);
class Addition extends MyTest
{
public void dispc()
void calculate(int a, int b)
{
{
System.out.println("method of class sum");
int x = a + b;
}
System.out.println("Sum= "+x);
}
}
}
class Ademo extends Sum
class Subtraction extends MyTest
{
{
public int sumOfTwo(int a,int b)
void calculate(int a, int b)
{
{
return a+b;
int y = a - b;
}
System.out.println("Subtract= "+y);
}
public int sumOfThree(int a,int b,int c)
}
{
class Multiplication extends MyTest
return a+b+c;
{
}
void calculate(int a, int b)
}
{
int z = a * b;
public class AbstractDemo
System.out.println("Multiply= "+z);
{
}
public static void main(String args[])
}
{
public class Example1
Ademo objs=new Ademo();
{
public static void main(String[] args)
int r1=objs.sumOfTwo(12,20);
{
int r2=objs.sumOfThree(4,5,17);
Addition a = new Addition();
Subtraction s = new Subtraction();
System.out.println("Sum of Two"+r1);
Multiplication m = new Multiplication();
System.out.println("Sum of Three"+r2);
a.calculate(20,30);
}
s.calculate(10,5);
}
m.calculate(10,20);
}
Example Explaination
}
MyTest
Abstract Method
calculate
Abstract Class
subclass1
subclass2
subclass2
Addition
Subtraction
Multiplication
calculate
calculate
calculate
Example
main
object1
object2
invoke object.subclassname(a.calculate(20,30))
object2
Final Keyword
stops value change,stops method overriding,stops
we must initialize the blank final variable in
Inheritances
Can be used along with Variables,methods and Classes.
constructor of the class otherwise it will throw
a compilation error.
Example2
Final Variable
1 are nothing but Constants
2 cannot change the value of a final variable
once it is initialzed.
Example1
package finalkey;
public class FKDemo1
{
final int max;
FKDemo1()
{
max=100;
}
void myMethod()
{
System.out.println(max);
}
public static void main(String args[])
{
FKDemo1 objFK=new FKDemo1();
objFK.myMethod();
}
package finalkey;
public class FKDemo
{
final int max=99;
void myMethod()
{
max=100;
}
public static void main(String args[])
{
FKDemo objFK=new FKDemo();
objFK.myMethod();
}
}
Program raise Exception
}
What is the use of Blank Final Variable?
Blank Final Variable,the final variable
Lets say we have a Student class which is having a field
that is not initialized at the time of
rollno.Since rollno should not be changed once the
student is registered,we can declare it as a final
declaration is known as blank final
variable in aclass.But we cannot initialize rollno in
Example3
package finalkey;
advance for all the students.In such case we can declare
rollno variable as blank final and we initialize this value
class StudentData{
public class FKDemo2
{
public static void main(String[] args) {
//Blank final variable
final int ROLL_NO;
StudentData(int rnum){
// create a final variable
final int AGE = 32;
//It must be initialized in constructor
ROLL_NO=rnum;
}
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
}
public static void main(String args[]){
}
StudentData obj=new StudentData(1234);
obj.myMethod();
Here we created a final variable named age. And tried to
change the value of the final variable.
When we run the program, we will get a compilation error with
the following message.
}
}
When we run the program, we will get a compilation error with
the following message.
cannot assign a value to final variable AGE
AGE = 45;
Example3
Final Method
1 A method cannot be overridden
which means even though a subclass can
2 call the final method of super class
without any issues but it cannot override
In the above example, we have created a final method named display() inside
the FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run
the program, we will get a compilation error with the following message.
display() in Main cannot override display() in FinalDemo
Example1
public final void display() {
^
package finalkey;
class FK
overridden method is final
{
final void msgm()
{
System.out.println("Iam Superclass final Method");
}
}
public class FkmDemo extends FK
{
void msgM()
{
System.out.println("Iam Subclass final Method");
}
public static void main(String args[])
{
FKmDemo objFK=new FKmDemo();
objFK.msgm();
}
}
package finalkey;
class FinalDemo
{
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
class FKmDemo1 extends FinalDemo {
// try to override final method
public final void display() {
System.out.println("The final method is
overridden.");
}
public static void main(String[] args) {
Generates an error
FKmDemo1 obj = new FKmDemo1);
obj.display();
Final Class
we cannot extend a final class
final class xyz
{
}
class Abc extends Xyz
{
}
Generates an error
}
}
Interface
An interface is a fully abstract class. It includes a group of abstract
methods (methods without a body).
We use the interface keyword to create an interface in Java
Example 1
Example 2
package interfaceexamples;
package interfaceexamples;
interface Polygon1 {
interface Language {
void getArea(int length, int breadth);
void getName(String name);
}
}
// implement the Polygon interface
// class implements interface
class Rectangle implements Polygon1 {
class ProgrammingLanguage implements Language {
// implementation of abstract method
// implementation of abstract method
public void getArea(int length, int breadth) {
public void getName(String name) {
System.out.println("Programming Language: " + name);
}
System.out.println("The area of the rectangle
is " + (length * breadth));
}
}
public class Name {
}
public static void main(String[] args) {
public class Polygon {
ProgrammingLanguage language = new ProgrammingLanguage();
public static void main(String[] args) {
language.getName("Java");
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
}
}
Programming Language: Java
The area of the rectangle is 30
In the above example, we have created an interface
named Language. The interface includes an abstract
Here,
method getName().
In the above example, we have created an
Here, the ProgrammingLanguage class implements the
interface named Polygon. The interface
interface and provides the implementation for the method.
contains an abstract method getArea().
Language is an interface.
It includes abstract
methods: getType() and getVersion().
Interface Vs Implementation
An interface is a set of action that an object can do. For example when you press a light switch, the
light goes on, you may not have cared how it splashed the light. In Object Oriented Programming
language, an Interface is a description of all functions that a class must have in order to be a new
interface. In our example, anything that "ACTS LIKE" a light, should have function definitions like
turn_on () and a turn_off (). The purpose of interfaces is to allow the computer to enforce the
properties of the class of TYPE T (whatever the interface is) must have functions called X, Y, Z, etc.
A class declaration combines the external interface (its local state) with an implementation of that
interface (the code that carries out the behaviour) . An object is an instance created from the class.
The interface defines an object’s visibility to the outside world.
The difference between interface and implementation is
In object oriented programs classes are the interface and how the object is processed and
executed is the implementation.
Characteristics of interface
·
The class template specifies the interfaces to enable an object to be created and operated properly.
·
An object's attributes and behaviour is controlled by sending functions to the object.
For example, let's take the example of increasing a car’s speed.
The person who drives the car doesn't care about the internal working. To increase the speed of the
car he just presses the accelerator to get the desired behaviour. Here the accelerator is the
interface between the driver (the calling / invoking object) and the engine (the called object) .
In this case, the function call would be Speed (70): This is the interface.
Internally, the engine of the car is doing all the things. It's where fuel, air, pressure, and electricity
come together to create the power to move the vehicle. All of these actions are separated from the
driver, who just wants to go faster. Thus we separate interface from implementation.
Difference between Abstract Class and Interface in Java
abstraction refers to hiding the internal implementation of the feature and only
showing the functionality to the users. i.e. what it works (showing), how it works
(hiding). Both abstract class and interface are used for abstraction, henceforth
Interface and Abstract Class are required prerequisites
package abstractexample;
import java.io.*;
//Class 1 //Helper abstract class
abstract class Shape1
{
String objectName ;// Declare fields
Shape1(String name)
// Constructor of this class
{
this.objectName = name;
}
public void moveTo(int x, int y)
{
System.out.println(this.objectName + " "+ "has been moved to"+ "
x = " + x + " and y = " + y);
}
abstract public double area();
abstract public void draw();
}
//Class 2
class Rectangle1 extends Shape1
//Helper class extending Class 1
{
int length, width;
Rectangle1(int length, int width, String name)
{
// Constructor
super(name);
// Super keyword refers to current instance itself
this.length = length;
this.width = width;
}
// this keyword refers to current instance itself
public void draw()
{
System.out.println("Rectangle has been drawn ");
}
public double area()
{
// Length * Breadth
return (double)(length * width);
}
}
class Circle2 extends Shape1 {
double pi = 3.14;
// Attributes of a Circle
int radius;
Circle2(int radius, String name)
// Constructor
{
super(name);
// Super keyword refers to parent class
this.radius = radius;
}
// This keyword refers to current instance itself
public void draw()
{
System.out.println("Circle has been drawn ");
}
public double area()
// Print statement
{
return (double)((pi * radius * radius));
}
}
class Avsi{
public static void main(String[] args)
// Main driver method
{
Shape1 rect = new Rectangle1(2,3,"Rectangle");
System.out.println("Area of rectangle: "+ rect.area());
rect.moveTo(1, 2);
System.out.println(" ");
// Creating the Objects of circle class
Shape1 circle = new Circle2(2, "Circle");
System.out.println("Area of circle: "+ circle.area());
circle.moveTo(2, 4);
}
}
Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2
Area of circle: 12.56
Circle has been moved to x = 2 and y = 4
What if we don’t have any common code between rectangle and
circle then go with the interface.
package abstractexample;
import java.io.*;
interface Shape
//Interface
{
void draw();
// Abstract method
double area();
}
class Rectangle implements Shape
{
//Class 1
//Helper class
int length, width;
Rectangle(int length, int width)
{
// constructor
this.length = length;
this.width = width;
}
public void draw()
{
System.out.println("Rectangle has been drawn ");
}
public double area()
{
return (double)(length * width);
}
}
class Circle implements Shape
{
//Helper class
double pi = 3.14;
//Class 2
int radius;
// constructor
Circle(int radius) { this.radius = radius; }
public void draw()
{
System.out.println("Circle has been drawn ");
}
public double area()
{
return (double)((pi * radius * radius));
}
}
class Avsi2 {
{
//Class 3
//Main class
// Main driver method
public static void main(String[] args)
{
// Creating the Object of Rectangle class
// and using shape interface reference.
Shape rect = new Rectangle(2, 3);
System.out.println("Area of rectangle: "
+ rect.area());
// Creating the Objects of circle class
Shape circle = new Circle(2);
System.out.println("Area of circle: "
+ circle.area());
}
}
Area of rectangle: 6.0
Area of circle: 12.56
The Catalog of Design Patterns
1
Creational patterns provide
Creational patterns
object creation mechanisms that
These patterns provide various object creation mechanisms,
increase flexibility and reuse of
which increase flexibility and reuse of existing code.
Structural patterns explain how
2
to assemble objects and classes
into larger structures, while
Behavioral patterns take care
3
of effective communication and
the assignment of
Define the skeleton of an algorithm in
an operation, deferring some steps to
subclasses. Template Method lets
subclasses redefine certain steps of
an algorithm without changing the
algorithm’s structure.
Structural patterns
Behavioral patterns
These patterns explain how to assemble objects
These patterns are concerned with
and classes into larger structures while keeping
algorithms and the assignment of
these structures flexible and efficient.
responsibilities between objects.
Template Method Design Pattern in JDK
All non-abstract methods of java.io.InputStream,
java.io.OutputStream, java.io.Reader and
java.io.Writer.
All non-abstract methods of
java.util.AbstractList, java.util.AbstractSet and
java.util.AbstractMap.
abstract class HouseTemplate
{
//template method, final so subclasses can't override
public final void buildHouse(){
buildFoundation();
buildPillars();
buildWalls();
buildWindows();
System.out.println("House is built.");
}
//default implementation
private void buildWindows() {
System.out.println("Building Glass Windows");
}
//methods to be implemented by subclasses
public abstract void buildWalls();
public abstract void buildPillars();
private void buildFoundation() {
System.out.println("Building foundation with cement,iron rods and sand");
}
}
class WoodenHouse extends HouseTemplate {
public void buildWalls() {
System.out.println("Building Wooden Walls");
}
public void buildPillars() {
System.out.println("Building Pillars with Wood coating");
}
}
class GlassHouse extends HouseTemplate {
public void buildWalls() {
System.out.println("Building Glass Walls");
}
public void buildPillars() {
System.out.println("Building Pillars with glass coating");
}
}
public class HousingClient {
public static void main(String[] args) {
HouseTemplate houseType = new WoodenHouse();
//using template method
houseType.buildHouse();
System.out.println("************");
houseType = new GlassHouse();
houseType.buildHouse();
}
}
abstract class CookRecipe
{
public void cookFood()
{
putStoveOn();
cutSpecificVegetable();
cookSpecificVegetable();
putStoveOff();
}
public void putStoveOn( )
{
System.out.println("Turn on the stove");
}
public void putStoveOff(){
System.out.println("Turn off the stove");
}
public abstract void cutSpecificVegetable();
public abstract void cookSpecificVegetable();
}
class CookCarrotRice extends CookRecipe{
public void cutSpecificVegetable( )
{
System.out.println("Cut Carrot");
}
public void cookSpecificVegetable( )
{
System.out.println("Boil and cook carrot rice");
}
}
class CookTomateoRice extends CookRecipe
{
public void cutSpecificVegetable( )
{
System.out.println("Cut Tomateo");
}
public void cookSpecificVegetable( )
{
System.out.println("Boil and cook tomateo rice");
}
}
public class CookingDemo
{
public static void main(String[] args)
{
System.out.println("Cook Carrot Rice");
CookRecipe crobj = new CookCarrotRice( );
crobj.cookFood( );
System.out.println("\nCook Tomateo Rice");
crobj = new CookTomateoRice( );
crobj.cookFood( );
}
Factory method is a creational design pattern
which solves the problem of creating product
objects without specifying their concrete classes.
Factory Method defines a method, which should be
used for creating objects instead of direct
constructor call (new operator). Subclasses can
package pattern;
abstract class CarTemplate {
protected String chassis;
protected String body;
protected String paint;
protected String interior;
public CarTemplate() {
super();
}
// steps
public abstract void fixChassis();
public abstract void fixBody();
public abstract void paint();
public abstract void fixInterior();
// template method
public void manufactureCar() {
fixChassis();
fixBody();
paint();
fixInterior();
}
public String getChassis() {
return chassis;
}
public void setChassis(String chassis) {
this.chassis = chassis;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getPaint() {
return paint;
}
public void setPaint(String paint) {
this.paint = paint;
}
public String getInterior() {
return interior;
}
public void setInterior(String interior) {
this.interior = interior;
}
@Override
public String toString() {
// StringBuilder class also uses Builder Design Pattern with implementation of
// java.lang.Appendable interface
StringBuilder builder = new StringBuilder();
builder.append("Car
[chassis=").append(chassis).append(",
.append(", interior=").append(interior).append("]");
return builder.toString();
}
}
class ClassicCar extends CarTemplate {
public ClassicCar() {
super();
}
@Override
public void fixChassis() {
System.out.println("Assembling chassis of the classical model");
this.chassis = "Classic Chassis";
}
@Override
public void fixBody() {
System.out.println("Assembling body of the classical model");
this.body = "Classic Body";
}
@Override
public void paint() {
System.out.println("Painting body of the classical model");
this.paint = "Classic White Paint";
}
@Override
public void fixInterior() {
System.out.println("Setting up interior of the classical model");
this.interior = "Classic interior";
}
}
class ModernCar extends CarTemplate {
public ModernCar() {
super();
}
@Override
public void fixChassis() {
System.out.println("Assembling chassis of the modern model");
this.chassis = "Modern Chassis";
}
@Override
public void fixBody() {
System.out.println("Assembling body of the modern model");
this.body = "Modern Body";
}
public void paint() {
System.out.println("Painting body of the modern model");
this.paint = "Modern Black Paint";
}
@Override
public void fixInterior() {
System.out.println("Setting up interior of the modern model");
this.interior = "Modern interior";
}
}
class SportsCar extends CarTemplate {
public SportsCar() {
super();
}
@Override
public void fixChassis() {
System.out.println("Assembling chassis of the sports model");
this.chassis = "Sporty Chassis";
}
@Override
public void fixBody() {
System.out.println("Assembling body of the sports model");
this.body = "Sporty Body";
}
@Override
public void paint() {
System.out.println("Painting body of the sports model");
this.paint = "Sporty Torch Red Paint";
}
@Override
public void fixInterior() {
System.out.println("Setting up interior of the sports model");
this.interior = "Sporty interior";
}
}
public class BuildCar {
public static void main(String[] args) {
CarTemplate car = new SportsCar();
car.manufactureCar();
if (car != null) {
System.out.println("Below car delievered: ");
System.out.println("================================");
System.out.println(car);
System.out.println("=================================");
}
}
}
package pattern;
import java.util.Scanner;
abstract class Car
{
abstract String carColor();
abstract String carModel();
}
class Suzuki extends Car {
public String carColor( )
{
return "Color : Red";
}
public String carModel( )
{
return "Suzuki Car Model is Suzuki 2019";
}
}
class Honda extends Car {
public String carColor( ) {
return "Color : Blue";
}
public String carModel( )
{
return "Honda Car Model is Honda 2021";
}
}
class Bmw extends Car
{
public String carColor( )
{
return "Color : White";
}
public String carModel( )
{
return "BMW Car Model is BMW 2020";
}
}
public class CarFactoryDemo {
public static Car getCarType(char choice)
{
Car ani=null;
if(choice == 'h')
ani = new Honda( );
else if(choice == 'd')
ani = new Suzuki( );
else if(choice == 'b')
ani = new Bmw( );
return ani;
}
public static void main(String[] args)
{
Scanner sobj = new Scanner(System.in);
Car cobj;
System.out.println("Welcome to Car Factory");
System.out.println("1.Honda(h)");
System.out.println("2.Suzuki(s)");
System.out.println("3.BMW(b)");
System.out.println("Enter u r choice :");
cobj = getCarType( sobj.next( ).charAt(0));
System.out.println(cobj.carModel( ));
System.out.println(cobj.carColor( ));
sobj.close( );
}
}
package pattern;
import java.util.Scanner;
abstract class Animal
{
abstract String getAnimal();
abstract String makeSound();
abstract String lifeSpan( );
}
class Lion extends Animal {
public String getAnimal( )
{
return "Animal : Lion";
}
public String makeSound( )
{
return "Sound : Roars";
}
public String lifeSpan( )
{
return "Life Span : 35";
}
}
class Cat extends Animal {
public String getAnimal( ) {
return "Animal : Cat";
}
public String makeSound( )
{
return "Sound : Meows";
}
public String lifeSpan( )
{
return "Life Span : 25";
}
}
class Dog extends Animal
{
public String getAnimal( )
{
return "Animal : Dog";
}
public String makeSound( )
{
return "Sound : Barks";
}
public String lifeSpan( )
{
return "Life Span : 22";
}
}
public class AnimalFactoryDemo
{
public static Animal getAnimalType(char choice)
{
Animal ani=null;
if(choice == 'l')
ani = new Lion( );
else if(choice == 'd')
ani = new Dog( );
else if(choice == 'c')
ani = new Cat( );
return ani;
}
public static void main(String[] args)
{
Scanner sobj = new Scanner(System.in);
Animal aobj;
System.out.println("Welcome to Animal Planet");
System.out.println("1.Lion(l)");
System.out.println("2.Dog(d)");
System.out.println("3.Cat(c)");
System.out.println("Enter u r choice :");
aobj = getAnimalType( sobj.next( ).charAt(0));
System.out.println(aobj.getAnimal( ));
System.out.println(aobj.makeSound( ));
}
System.out.println(aobj.lifeSpan( ));
sobj.close( );
}
The Java Generics allows us to create a single class, interface,
and method that can be used with different types of data
(objects).
This helps us to reuse our code.
Java Generics is a set of related methods or a set of similar types. Generics
allow types Integer, String, or even user-defined types to be passed as a
parameter to classes, methods, or interfaces. Generics are mostly used by
classes like HashSet or HashMap.
Java Generics Class
We can create a class that can be used with any type of data. Such a
class is known as Generics Class.
Java Generics Method
Similar to the generics class, we can also create a method that can be
used with any type of data. Such a class is known as Generics Method.
package generic26;
public class container<T> {
private T obj1;
public void add(T obj1) {
this.obj1 = obj1;
}
public T get() {
return obj1;
}
public static void main(String[] args) {
container<Integer> integercontainer= new container<Integer>();
container<String> stringcontainer = new container<String>();
integercontainer.add(new Integer(7));
stringcontainer.add(new String("You are awesome"));
System.out.printf("Integer Value :%d\n\n", integercontainer.get());
System.out.printf("String Value :%s\n", stringcontainer.get());
}
}
package generic26;
public class Example1 {
public static void main(String[] args) {
// initialize generic class
// with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
// initialize generic class
// with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
}
// create a generics class
class GenericsClass<T> {
// variable of T type
private T data;
public GenericsClass(T data) {
this.data = data;
}
// method that return T type variable
public T getData() {
return this.data;
}
}
package generic26;
public class Example2 {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
// generics method working with String
demo.<String>genericsMethod("Java Programming");
// generics method working with integer
demo.<Integer>genericsMethod(25);
}
}
class DemoClass {
// creae a generics method
public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
}
package generic26;
public class Example3 {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] integerArray = { 5, 4, 3, 2, 1 };
Double[] doubleArray = { 1.21, 22.12, 13.32 };
Character[] characterArray = { 'Y', 'o', 'u', ' ',
'a', 'r', 'e', ' ', 'a','w','e','s','o','m','e' };
System.out.println("integerArray contains:");
printArray(integerArray); // pass an Integer array
System.out.println("\ndoubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\n characterArray contains:");
printArray(characterArray); // pass a Character array
}
}
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Class: A class is a group of objects which have common properties
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
single, multilevel and hierarchical.
Example1
package inherit;
class Employee7
{
float salary=40000;
}
public class Programmer extends Employee7
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Example 3 MultiLevel Inheritance
package inherit;
class CollegeM
{
void admission()
{
System.out.println("get Admitted");
}
}
class StudentM extends CollegeM
{
void branch()
{
System.out.println("Select Branch");
}
}
class SemM extends StudentM
{
void result()
{
System.out.println("passed");
}
}
public class MultiInherit
{
public static void main(String args[])
{
SemM sm=new SemM();
sm.result();
sm.branch();
sm.admission();
}
}
Example 5
package inherit;
class StudentY20
{
int year=2021;
String collegename="KLU";
void does()
{
System.out.println("Studying");
}
}
public class Student2021 extends StudentY20
{
String branch="CSE";
public static void main(String args[])
{
Student2021 s2021=new Student2021();
System.out.println(s2021.collegename);
System.out.println(s2021.year);
System.out.println(s2021.branch);
s2021.does();
}
}
Example 2 Single Inheritance
package inherit;
class Office
{
void admission()
{
System.out.println("get admitted");
}
}
class Student1 extends Office
{
void branch()
{
System.out.println("select branch");
}
}
public class College7 {
public static void main(String args[])
{
Student1 s=new Student1();
s.admission();
s.branch();
}
}
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Example 4 Hierarchical Inheritance
package inherit;
class CollegeH
{
void admission()
{
System.out.println("get Admitted");
}
}
class StudentH extends CollegeH
{
void branch()
{
System.out.println("Select Branch");
}
}
class RollH extends CollegeH
{
void no()
{
System.out.println("get Reg.NO");
}
}
public class HierarInherit
{
public static void main(String args[])
{
RollH rh=new RollH();
rh.no();
rh.admission();
}
}
private members can only be accessed using public or protected getter
and setter methods of super class
Example 6
package inherit;
class StudentY20E
{
private int year;
private String collegename;
public void setYear(int pyear)
{
this.year=pyear;
}
public int getYear()
{
return year;
}
public void setCollegeName(String pcollegename)
{
this.collegename=pcollegename;
}
public String getCollegeName()
{
return collegename;
}
void does()
{
System.out.println("Studying");
}
}
public class Student2021E extends StudentY20E
{
String branch="CSE";
public static void main(String args[])
{
Student2021 s2021=new Student2021();
System.out.println(s2021.collegename);
System.out.println(s2021.year);
System.out.println(s2021.branch);
s2021.does();
}
}
Comparable
Comparable is an interface defining a strategy of comparing an
object with other objects of the same type. This is called the
class's “natural ordering.”
To create a Comparator, we have to implement the Comparator interface.
Comparator
The Comparator interface defines a compare(arg1,
arg2) method with two arguments that represent compared objects,
and works similarly to the Comparable.compareTo() method.
package interfaceexamples;
import java.util.*;
class Student implements Comparable<Student>
{
private int sno;
private int age;
private String sname;
public void setData(int sno,int age,String sname)
{
this.sno=sno;
this.age=age;
this.sname=sname;
}
public int getSno()
{
return sno;
}
public int getAge()
{
return age;
}
public String getSname()
{
return sname;
}
public String toString()
{
return "Sno "+getSno()+"
Sname "+getSname()+"
Age "+getAge();
}
public int compareTo(Student a)
{
if(this.age>a.age)
return 1;
else if(this.age==a.age)
return 0;
else
return -1;
}
}
public class StudentMenu
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
LinkedList<Student> st=new LinkedList<Student>();
boolean repeat =true;
int sno,age,choice;
String sname;
while(repeat)
{
System.out.println("1. add new record
System.out.println("enter your choice");
choice=s.nextInt();
if(choice==1)
{
Student temp=new Student();
2. display 3. sort by age 4. Exit");
System.out.println("enter sno age and name");
sno=s.nextInt();
age=s.nextInt();
s.nextLine();
sname=s.next();
temp.setData(sno,age,sname);
st.add(temp);
}
else if(choice==2)
{
for(int i=0;i<st.size();i++)
{
System.out.println(st.get(i));
}
}
else if(choice==3)
{
Collections.sort(st);
}
else
repeat=false;
}
}
}
package interfaceexamples;
import java.util.*;
class StudentDetails
{
int sno,age;
String sname;
StudentDetails(int sno,int age,String sname)
{
this .sno=sno;
this.age=age;
this.sname=sname;
}
public String toString()
{
return "Sno "+sno+"Age "+age+"Sname "+sname;
}
}
class SortBySno implements Comparator<StudentDetails>
{
public int compare(StudentDetails a,StudentDetails b)
{
if(a.sno==b.sno)
return 0;
else if (a.sno<b.sno)
return -1;
else
return 1;
}
}
class SortByAge implements Comparator<StudentDetails>
{
public int compare(StudentDetails a,StudentDetails b)
{
if(a.age==b.age)
return 0;
else if (a.age<b.age)
return -1;
else
return 1;
}
}
class SortBySname implements Comparator<StudentDetails>
{
public int compare(StudentDetails a,StudentDetails b)
{
return a.sname.compareTo(b.sname);
}
}
public class StudentSort {
public static void main(String args[])
{
int sno,age,choice;
String sname;
boolean repeat =true;
Scanner s=new Scanner(System.in);
ArrayList<StudentDetails> st=new ArrayList<StudentDetails>();
while(repeat)
{
System.out.println("1.add new 2. sort by name 3.sort by age 4.sort by sno 5.Exit");
System.out.println("enter choice");
choice=s.nextInt();
if(choice==1)
{
System.out.println("enter sno age and sname");
sno=s.nextInt();
age=s.nextInt();
s.nextLine();
sname=s.next();
st.add(new StudentDetails(sno,age,sname));
}
else if(choice==2)
{
Collections.sort(st,new SortBySname());
for(int i=0;i<st.size();i++ )
{
System.out.println(st.get(i));
}
}
else if(choice==3)
{
Collections.sort(st,new SortByAge());
for(int i=0;i<st.size();i++ )
{
System.out.println(st.get(i));
}
}
else if(choice==4)
{
Collections.sort(st,new SortBySno());
for(int i=0;i<st.size();i++ )
{
System.out.println(st.get(i));
}
}
else
repeat=false;
}
}
}
A vector can be defined as a dynamic array that can grow or
shrink on its own i.e. vector will grow when more elements
This behavior is unlike that of arrays which are static. But
similar to arrays, vector elements can be accessed using
A vector can be viewed as similar to another dynamic array data
structure, ArrayList except for the two below differences:
The vector is synchronized i.e. all the methods in Vector are marked
‘synchronized’ and thus once a method is invoked, the same method
The vector class has many methods that are not a part of the
collections framework but its legacy methods.
A Vector class is apart of the “java.util ” package and implements
List interface. A Vector is an array of objects or vector of objects.
Vector object = new Vector();
For Example,
(i) Vector()
Vector vec1 = new Vector ();
(ii) Vector(int initialCapacity)
Vector vec1 = new Vector (10);
(iii) Vector(int initialCapacity, int capacityIncrement)
Vector object = new Vector (initialCapacity,
capacityIncrement);
package vector26;
import java.util.*;
public class Vec{
public static void main(String[] args) {
//Create vectors v1, v2,v3 and v4
Vector v1 = new Vector(); //a vector with default constructor
Vector v2 = new Vector(20); // a vector of given Size
//initialize vector v2 with values
v2.add(10);
v2.add(20);
v2.add(30);
Vector v3 = new Vector(30, 10); // a vector of given Size and Increment
// create a vector v4 with given collection
List<String> aList = new ArrayList<>();
aList.add("one");
aList.add("two");
Vector v4 = new Vector(aList);
//print contents of each vector
System.out.println("Vector v1 Contents:" + v1);
System.out.println("Vector v2 Contents:" + v2);
System.out.println("Vector v3 Contents:" + v3);
System.out.println("Vector v4 Contents:" + v4);
}
}
package vector26;
import java.util.*;
public class Vec1 {
public static void main(String args[]) {
// create a vector with initial capacity = 2
Vector<String> fruits_vec = new Vector<String>(2);
//add elements to the vector
fruits_vec.addElement("Grapes");
fruits_vec.addElement("Melon");
fruits_vec.addElement("Kiwi");
fruits_vec.addElement("Apple");
//print current size and capacity of the vector
System.out.println("Vector Size: "+fruits_vec.size());
System.out.println("Default Vector capacity increment: "+fruits_vec.capacity());
//add more elements to the vector
fruits_vec.addElement("Orange");
fruits_vec.addElement("Mango");
fruits_vec.addElement("Fig");
//print current size and capacity again
System.out.println("Vector Size after addition: "+fruits_vec.size());
System.out.println("Vector Capacity after increment: "+fruits_vec.capacity());
//print vector elements
Enumeration fruits_enum = fruits_vec.elements();
System.out.println("\nVector Elements are:");
while(fruits_enum.hasMoreElements())
System.out.print(fruits_enum.nextElement() + " ");
}
}
package vector26;
import java.util.*;
public class Vec2 {
public static void main(String args[]) {
//Create an empty Vector of even numbers
Vector < Integer > evenVector= new Vector <> ();
//Add elements in the vector
evenVector.add(2);
evenVector.add(4);
evenVector.add(6);
evenVector.add(8);
evenVector.add(10);
evenVector.add(12);
evenVector.add(14);
evenVector.add(16);
//Display the vector
System.out.println("Vector evenVector contents: " +evenVector);
//delete the first occurence of an element 4 using remove method
System.out.println("\nFirstoccurence of element 4 removed:
"+evenVector.remove((Integer)4));
System.out.println("\nVector contents after remove operation: " +evenVector);
//Remove the element at index 4 & display the vector
System.out.println("\nRemove element at index 4: " +evenVector.remove(4));
System.out.println("\nVector contents after remove: " +evenVector);
//hashcode for the vector
System.out.println("\nHash code of the vector = "+evenVector.hashCode());
//Get the element at index 1
System.out.println("\nElement at index 1 is = "+evenVector.get(1));
}
}
package vector26;
import java.util.*;
public class Vsort {
public static void main(String arg[]) {
//Create an empty vector
Vector<Integer> oddVector = new Vector<>();
//Add elements to the vector
oddVector.add(1);
oddVector.add(11);
oddVector.add(7);
oddVector.add(3);
oddVector.add(5);
//print the vector elements
System.out.println("Vector elements: "+oddVector);
//sort vector using Collections.sort method
Collections.sort(oddVector);
//print sorted vector
System.out.println("Vector elements after sorting: "+oddVector);
}
}
package vector26;
import java.util.*;
public class Vsort1 {
public static void main(String args[]) {
//define and initialize a vector
Vector inner_vec = new Vector();
inner_vec.add("Computational");
inner_vec.add("Thinking");
inner_vec.add("Object Oriented");
inner_vec.add("Design");
//define another vector and add first vector to it.
Vector outer_vec = new Vector();
outer_vec.add(inner_vec);
String str;
//display the contents of vector of vectors
System.out.println("Contents of vector of vectors:");
for(int i=0;i<inner_vec.size();i++){
str = (String) ((Vector) outer_vec.get(0)).get(i);
System.out.print(str + " ");
}
}
}
package vector26;
import java.util.Vector;
public class VtoA {
public static void main(String[] args) {
// Create a Vector of String elements
Vector<String> color_vector = new Vector<String>();
// Add elements to Vector
color_vector.add("Violet");
color_vector.add("Indigo");
color_vector.add("Blue");
color_vector.add("Green");
color_vector.add("Yellow");
color_vector.add("Orange");
color_vector.add("Red");
//Convert Vector to String Array using toArray method
String[] colorsArray = color_vector.toArray(new String[color_vector.size()]);
//print Array Elements
System.out.println("String Array Elements :");
for(String val:colorsArray){
System.out.print(val + " ");
}
}
}
Download