/**
* Pyramid - Nested For Loop Example
*
* This example shows how to generate a pyramid like the one shown below using
* simple Java for loop
*
* *****
* ****
* ***
* **
* *
* *
* **
* ***
* ****
* *****
*
*
*
*/
public class PyramidNestedForLoopExample_4 {
public static void main(String[] args) {
// generate first-half of the pyramid
for(int i=5; i>0 ;i--){
for(int j=0; j < i; j++){
// display/add star
System.out.print("*");
}
//create a new line
System.out.println("");
}// end of for loop
// generate second-half of the pyramid
for(int i=1; i<= 5 ;i++){
for(int j=0; j < i; j++){
// display/add star
System.out.print("*");
}
//create a new line
System.out.println("");
}// end of for loop
}
}
=====================================
// generate first-half of the pyramid
for(int i=5; i>=1;i--){
for(int j=1; j <= i; j++){
// display/add star
System.out.print(j);
}
System.out.println("");
}
-------------------------------------------------------------
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:- class A{}
- class B extends A{}
- A a=new B();//upcasting
Example of Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar. Splendar 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, subclass method is invoked at runtime.Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
- class Bike{
- void run(){System.out.println("running");}
- }
- class Splender extends Bike{
- void run(){System.out.println("running safely with 60km");}
- public static void main(String args[]){
- Bike b = new Splender();//upcasting
- b.run();
- }
- }
Output:running safely with 60km.
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.Note: It is also given in method overriding but there was no upcasting.
- class Bank{
- int getRateOfInterest(){return 0;}
- }
- class SBI extends Bank{
- int getRateOfInterest(){return 8;}
- }
- class ICICI extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class AXIS extends Bank{
- int getRateOfInterest(){return 9;}
- }
- class Test3{
- public static void main(String args[]){
- Bank b1=new SBI();
- Bank b2=new ICICI();
- Bank b3=new AXIS();
- System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
- System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
- System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
- }
- }
Output: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
Runtime Polymorphism with data member
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members. |
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always. |
Rule: Runtime polymorphism can't be achieved by data members.
- class Bike{
- int speedlimit=90;
- }
- class Honda3 extends Bike{
- int speedlimit=150;
- public static void main(String args[]){
- Bike obj=new Honda3();
- System.out.println(obj.speedlimit);//90
- }
Output:90
Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.- class Animal{
- void eat(){System.out.println("eating");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("eating fruits");}
- }
- class BabyDog extends Dog{
- void eat(){System.out.println("drinking milk");}
- public static void main(String args[]){
- Animal a1,a2,a3;
- a1=new Animal();
- a2=new Dog();
- a3=new BabyDog();
- a1.eat();
- a2.eat();
- a3.eat();
- }
- }
Output: eating eating fruits drinking Milk
Try for Output
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
- }
- class BabyDog1 extends Dog{
- public static void main(String args[]){
- Animal a=new BabyDog1();
- a.eat();
- }}
Output: Dog is eating
--------------------------------------------------------------------------------------------------------
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.There are two types of binding
- static binding (also known as early binding).
- dynamic binding (also known as late binding).
Understanding Type
Let's understand the type of instance.1) variables have a type
Each variable has a type, it may be primitive and non-primitive.- int data=30;
2) References have a type
- class Dog{
- public static void main(String args[]){
- Dog d1;//Here d1 is a type of Dog
- }
- }
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass. |
- class Animal{}
- class Dog extends Animal{
- public static void main(String args[]){
- Dog d1=new Dog();
- }
- }
Here d1 is an instance of Dog class, but it is also an instance of Animal. |
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.If there is any private, final or static method in a class, there is static binding.
Example of static binding
- class Dog{
- private void eat(){System.out.println("dog is eating...");}
- public static void main(String args[]){
- Dog d1=new Dog();
- d1.eat();
- }
- }
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.Example of dynamic binding
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
- public static void main(String args[]){
- Animal a=new Dog();
- a.eat();
- }
- }
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type. |
---------------------------------------
-----------------------------------------
------------------------------------------
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.- It is used to achieve fully abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class. |
- interface printable{
- void print();
- }
- class A6 implements printable{
- public void print(){System.out.println("Hello");}
- public static void main(String args[]){
- A6 obj = new A6();
- obj.print();
- }
- }
Output:Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.- interface Printable{
- void print();
- }
- interface Showable{
- void show();
- }
- class A7 implements Printable,Showable{
- public void print(){System.out.println("Hello");}
- public void show(){System.out.println("Welcome");}
- public static void main(String args[]){
- A7 obj = new A7();
- obj.print();
- obj.show();
- }
- }
Output:Hello Welcome
Q) Multiple inheritance is not supported through class in java but it is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. For example: |
- interface Printable{
- void print();
- }
- interface Showable{
- void print();
- }
- class testinterface1 implements Printable,Showable{
- public void print(){System.out.println("Hello");}
- public static void main(String args[]){
- testinterface1 obj = new testinterface1();
- obj.print();
- }
- }
Hello
Interface inheritance
A class implements interface but one interface extends another interface .- interface Printable{
- void print();
- }
- interface Showable extends Printable{
- void show();
- }
- class Testinterface2 implements Showable{
- public void print(){System.out.println("Hello");}
- public void show(){System.out.println("Welcome");}
- public static void main(String args[]){
- Testinterface2 obj = new Testinterface2();
- obj.print();
- obj.show();
- }
- }
Hello Welcome
Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.- //How Serializable interface is written?
- public interface Serializable{
- }
Nested Interface in Java
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:- interface printable{
- void print();
- interface MessagePrintable{
- void msg();
- }
- }
-----------------------------------------------------------
----------------------------------------------------
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.Another way, it shows only important things to the user and hides the internal details for example sending sms, you just 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.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java- Abstract class (0 to 100%)
- Interface (100%)
Abstract class in Java
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.Example abstract class
- abstract class A{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method. |
Example abstract method
- abstract void printStatus();//no body and abstract
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.- 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();
- }
- }
running safely..
Understanding the real scenario of abstract class
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.A factory method is the 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.
File: TestAbstraction1.java
- 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 real scenario, object is provided through method e.g. getShape() method
- s.draw();
- }
- }
drawing circle
Another example of abstract class in java
File: TestBank.java
- abstract class Bank{
- abstract int getRateOfInterest();
- }
- class SBI extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class PNB extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class TestBank{
- public static void main(String args[]){
- Bank b=new SBI();//if object is PNB, method of PNB will be invoked
- int interest=b.getRateOfInterest();
- System.out.println("Rate of Interest is: "+interest+" %");
- }}
Rate of Interest is: 7 %
Abstract class having constructor, data member, methods etc.
An abstract class can have data member, abstract method, method body, constructor and even main() method.
File: TestAbstraction2.java
- //example of abstract class that have method body
- abstract class Bike{
- Bike(){System.out.println("bike is created");}
- abstract void run();
- void changeGear(){System.out.println("gear changed");}
- }
- class Honda extends Bike{
- void run(){System.out.println("running safely..");}
- }
- class TestAbstraction2{
- public static void main(String args[]){
- Bike obj = new Honda();
- obj.run();
- obj.changeGear();
- }
- }
bike is created running safely.. gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
- class Bike12{
- abstract void run();
- }
compile time error
Rule: If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.
Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interface. In such case, the end user may not be forced to override all the methods of the interface.Note: If you are beginner to java, learn interface first and skip this example.
- 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();
- }}
Output:I am a I am b I am c I am d
No comments:
Post a Comment