OOPS:-
1. Abstraction:-
Hiding the implementation
and only showing functionality to the user.
//Example of Abstract class that has
an abstract method
/*In this example, Bike is an
abstract class that contains only one abstract method run.
Its implementation is provided by the Honda
class.*/
package Abstraction;
abstract class Bike {
abstract void run();
}
class Honda4 extends Bike {
void run() {
System.out.println("running
safely");
}
public static void main(String args[])
{
Bike
obj = new Honda4();
obj.run();
}
}
o/p:-
running safely
//Understanding the real scenario of
Abstract class
/* In this example, Shape is the
abstract class, and its implementation is provided by the Rectangle and Circle
classes.
Mostly, we don't know about the implementation
class (which is hidden to the end user), and an object of the implementation
class is provided by the factory method.
A factory method is a method that returns the
instance of the class. We will learn about the factory method later.
In this example, if you create the instance of
Rectangle class, draw() method of Rectangle class will be invoked. */
package Abstraction;
abstract class Shape {
abstract void draw();
}
// In real scenario, implementation
is provided by others i.e. unknown by end
// user
class Rectangle extends Shape {
void draw() {
System.out.println("drawing
rectangle");
}
}
class Circle1 extends Shape {
void draw() {
System.out.println("drawing
circle");
}
}
// In real scenario, method is
called by programmer or user
class TestAbstraction1 {
public static void main(String args[])
{
Shape
s = new Circle1();// In a real
scenario, object is provided
// through method,
e.g., getShape() method
s.draw();
Rectangle
r = new Rectangle();
r.draw();
}
}
//Another example of Abstract class in java
//Example main bank and sub banks
package Abstraction;
abstract class Bank {
abstract
int getRateOfInterest();
}
class SBI extends Bank {
int
getRateOfInterest() {
return
7;
}
}
class PNB extends Bank {
int
getRateOfInterest() {
return
8;
}
}
class TestBank {
public
static void main(String args[]) {
Bank
b;
b
= new SBI();
System.out.println("Rate
of Interest is: " + b.getRateOfInterest()
+
" %");
b
= new PNB();
System.out.println("Rate
of Interest is: " + b.getRateOfInterest()
+
" %");
}
}
//Abstract class having constructor,
data member and methods
package Abstractionn;
abstract class Bike {
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear() {
System.out.println("gear
changed");
}
}
// Creating a Child class which
inherits Abstract class
class Honda extends Bike {
void run() {
System.out.println("running
safely..");
}
}
// Creating a Test class which calls
abstract and non-abstract methods
class TestAbstraction2 {
public static void main(String args[])
{
Bike
obj = new Honda();
obj.run();
obj.changeGear();
}
}
// Rule: If there is an abstract
method in a class, that class must be abstract.
// Rule: If you are extending an
abstract class that has an abstract method, you
// must either provide the
implementation of the method or make this class
// abstract.
package Abstractionn;
interface A {
void a();
void b();
void c();
void d();
}
abstract class B implements A {
public void c() {
System.out.println("I am c");
}
}
class M extends B {
public void a() {
System.out.println("I am a");
}
public void b() {
System.out.println("I am b");
}
public void d() {
System.out.println("I am d");
}
}
class Test5 {
public static void main(String args[])
{
A
a = new M();
a.a();
a.b();
a.c();
a.d();
}
}
2. Encapsulation:-
Making the fields in
a class private and providing access to the fields via public methods.
//Programmer is the subclass and
Employee is the superclass. The relationship between the two classes is
Programmer IS-A Employee. It means that Programmer is a type of Employee.
package Encapsulation1;
class Employee {
float salary = 40000;
}
class Programmer extends Employee {
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);
}
}
// Note: Multiple inheritance is not supported in Java
through class.
o/p:-
Programmer salary is:40000.0
Bonus of Programmer is:10000
Student.java
//A Java class which
is a fully encapsulated class.
//It has a private
data member and getter and setter methods.
package
Encapsulation1;
public class Student
{
// private data member
private String name;
// getter method for name
public String getName() {
return name;
}
// setter method for name
public void setName(String name)
{
this.name =
name;
}
}// class
Test.java
//A Java class to test the
encapsulated class.
package Encapsulation1;
class Test {
public static void main(String[] args)
{
// creating
instance of the encapsulated class
Student
s = new Student();
// setting value in
the name member
s.setName("vijay");
// getting value of
the name member
System.out.println(s.getName());
}
}// class
o/p:-
Vijay
3. Inheritance:-
One object acquires
the properties of another.
Programmer.java
//Programmer is the subclass and
Employee is the superclass. The relationship between the two classes is
Programmer IS-A Employee. It means that Programmer is a type of Employee.
package Encapsulation1;
class Employee {
float salary = 40000;
}
class Programmer extends Employee {
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);
}
}
// Note: Multiple inheritance is not supported in Java
through class.
Single
Inheritance Example
File: TestInheritance.java
1.
class Animal{
2.
void eat(){System.out.println("eating...");}
3.
}
4.
class Dog extends Animal{
5.
void bark(){System.out.println("barking...");}
6.
}
7.
class TestInheritance{
8.
public static void main(String args[]){
9.
Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
Multilevel
Inheritance Example
File: TestInheritance2.java
1.
class Animal{
2.
void eat(){System.out.println("eating...");}
3.
}
4.
class Dog extends Animal{
5.
void bark(){System.out.println("barking...");}
6.
}
7.
class BabyDog extends Dog{
8.
void weep(){System.out.println("weeping...");}
9.
}
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
Hierarchical
Inheritance Example
File: TestInheritance3.java
1.
class Animal{
2.
void eat(){System.out.println("eating...");}
3.
}
4.
class Dog extends Animal{
5.
void bark(){System.out.println("barking...");}
6.
}
7.
class Cat extends Animal{
8.
void meow(){System.out.println("meowing...");}
9.
}
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Q) Why
multiple inheritance is not supported in java?
To reduce the complexity and simplify the
language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three
classes. The C class inherits A and B classes. If A and B classes have the same
method and you call it from child class object, there will be ambiguity to call
the method of A or B class.
Since compile-time errors are better than
runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.
1.
class A{
2.
void msg(){System.out.println("Hello");}
3.
}
4.
class B{
5.
void msg(){System.out.println("Welcome");}
6.
}
7.
class C extends A,B{//suppose if it were
8.
9.
public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Compile Time Error
Test5.java
//Example of abstract class and
interface in Java:-
package Interface;
//Creating interface that has 4
methods
interface A {
void a();// bydefault,
public and abstract
void b();
void c();
void d();
}
// Creating abstract class that
provides the implementation of one method of A
// interface
abstract class B implements A {
public void c() {
System.out.println("I am C");
}
}
// Creating subclass of abstract
class, now we need to provide the
// implementation of rest of the
methods
class M extends B {
public void a() {
System.out.println("I am a");
}
public void b() {
System.out.println("I am b");
}
public void d() {
System.out.println("I am d");
}
}
// Creating a test class that calls
the methods of A interface
class Test5 {
public static void main(String args[])
{
A
a = new M();
a.a();
a.b();
a.c();
a.d();
}
}
o/p:-
I am a
I am b
I am C
I am d
TestInterface4.java
package Interface;
interface Printable {
void print();
}
interface Showable extends Printable {
void show();
}
class TestInterface4 implements Showable {
public void print() {
System.out.println("Hello");
}
public void show() {
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
o/p:-
Hello
Welcome
Aggregation in Java
If a class have an entity reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.
Consider a situation, Em
Consider a situation, Employee object contains many informations
such as id, name, emailId etc. It contains one more object named address, which
contains its own informations such as city, state, country, zipcode etc. as
given below.
1.
class Employee{
2.
int id;
3.
String name;
4.
Address address;//Address is a class
5.
...
6.
}
In such case, Employee has an entity reference address, so relationship
is Employee HAS-A address.
Why use
Aggregation?
- For
Code Reusability.
Simple
Example of Aggregation

In this example, we have created the reference of Operation class
in the Circle class.
1.
class Operation{
2.
int square(int n){
3.
return n*n;
4.
}
5.
}
6.
7.
class Circle{
8.
Operation op;//aggregation
9.
double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Output:78.5
When use
Aggregation?
- Code
reuse is also best achieved by aggregation when there is no is-a
relationship.
- Inheritance
should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best
choice.
Understanding
meaningful example of Aggregation
In this example, Employee has an object of Address, address object
contains its own informations such as city, state, country etc. In such case
relationship is Employee HAS-A address.
Address.java
1.
public class Address {
2.
String city,state,country;
3.
4.
public Address(String city, String state, String country) {
5.
this.city = city;
6.
this.state = state;
7.
this.country = country;
8.
}
9.
10. }
Emp.java
1.
public class Emp {
2.
int id;
3.
String name;
4.
Address address;
5.
6.
public Emp(int id, String name,Address address) {
7.
this.id = id;
8.
this.name = name;
9.
this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Output:111 varun
gzb UP india
112 arun
gno UP india
4. Polymorphism:-
When a parent class
reference is used to refer to a child class object.
Splendor.java
//Example of Java
Runtime Polymorphism
/*In this example, we
are creating two classes Bike and Splendor. Splendor class extends Bike class
and overrides its run() method. We are calling the run method by the reference
variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at
runtime.
Since method invocation is determined by the
JVM not compiler, it is known as runtime polymorphism.*/
package Polymorphism;
class Bike {
void run() {
System.out.println("running");
}
}
class Splendor
extends Bike {
void run() {
System.out.println("running
safely with 60km");
}
public static void main(String
args[]) {
Bike b = new
Splendor();// upcasting
b.run();
}
}
running safely with 60km
TestPolymorphism2.java
//Java Runtime Polymorphism
Example: Shape
package Polymorphism;
class Shape {
void draw() {
System.out.println("drawing...");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("drawing
rectangle...");
}
}
class Circle extends Shape {
void draw() {
System.out.println("drawing
circle...");
}
}
class Triangle extends Shape {
void draw() {
System.out.println("drawing
triangle...");
}
}
class TestPolymorphism2 {
public static void main(String args[])
{
Shape
s;
s
= new Rectangle();
s.draw();
s
= new Circle();
s.draw();
s
= new Triangle();
s.draw();
}
}
TestPolymorphism3.java
//Java Runtime Polymorphism
Example: Animal
package Polymorphism;
class Animal {
void eat() {
System.out.println("eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("eating
bread...");
}
}
class Cat extends Animal {
void eat() {
System.out.println("eating
rat...");
}
}
class Lion extends Animal {
void eat() {
System.out.println("eating
meat...");
}
}
class TestPolymorphism3 {
public static void main(String[] args)
{
Animal
a;
a
= new Dog();
a.eat();
a
= new Cat();
a.eat();
a
= new Lion();
a.eat();
}
}
Nice tutorial
ReplyDelete