Friday, 16 October 2015

Overriding Method

What is Method Overriding?

Method Overriding in Java occurs when a subclass provides a specific implementation of a method that is already defined in its superclass, using the same method name and same parameter list (method signature).

  • It is used to achieve runtime polymorphism.
  • It allows a subclass to provide its own implementation of an inherited method without modifying the parent class code.

Rules for Method Overriding :
  1. Method Name → Must be the same as the superclass method.

  2. Parameters → Must have the same number and type of parameters.

  3. Access Modifier → Cannot be more restrictive than the superclass method.

    • Restriction order: private ⟹ default ⟹ protected ⟹ public

  4. Return Type → Must be the same or a covariant return type (subclass of the parent’s return type).

  5. Exceptions → Overriding methods can throw unchecked exceptions, but for checked exceptions, the subclass method cannot throw broader or new checked exceptions that the parent method doesn’t declare. Check ๐Ÿ‘‰here in details.

Examples of Method Overriding :

Case 1: By Method Name


package com.tutorial4u;

class Animal{
       public void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
       @Override
       public void display() {
             System.out.println("I am a cat.");
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  //Output : From Super Class
             Cat cat = new Cat();
             cat.display(); //Output : From Sub Class
             Animal animal1 = new Cat();

             animal1.display();// Output from sub class
       }

}

Output :
I am an animal.
I am a cat.
I am a cat.

Case 2: Access Modifier 

(A) Increasing visibility → Allowed

package com.tutorial4u;

class Animal{
       protected void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
       public void display() {
             System.out.println("I am a cat.");
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  //Output : From Super Class
             Cat cat = new Cat();
             cat.display(); //Output : From Sub Class
       }

}

Output

I am an animal.
I am a cat..

(B)Reducing visibility → Compilation Error

package com.tutorial4u;

class Animal{
       protected void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
       //Compilation Error, Cannot reduce the visibility of the inherited method from Animal

       //here visibility must be protected or public but not private or default.
       private void display() {
             System.out.println("I am a cat.");
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  
             Cat cat = new Cat();
             cat.display(); 
       }
}

Note: ๐Ÿ‘‰ The subclass cannot override the method with a more restrictive access modifier.

Output :
Compilation Error, Cannot reduce the visibility of the inherited method from Animal
Case 3: Changing the Number of Parameters (NOT Overriding)

package com.tutorial4u;

class Animal{
       public void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
// This is Overloading, not Overriding
       public void display(int i) {
             System.out.println(i);
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  //Output : From Super Class
             Cat cat = new Cat();
             cat.display(); //Output : From super class
             cat.display(10);
       }
}

Output :

I am an animal.
I am an animal.
10
Note : ๐Ÿ‘‰ Changing the number or type of parameters creates Overloading, not Overriding.

You must not change the arguments of a method in the subclass. If you change the number or types of arguments of the overridden method in the subclass, then it will result in method overloading, not method overriding.

Case 4:  Return Type 
You can only return same type or a subclass of the parents return type , it is known as covariant return type. 

Example : 
package com.tutorial4u;

class A {
}

class B extends A {
}

class Super {
       public A m() {
             System.out.println("Super class method");
             return new A();
       }
}

class Children extends Super {
       public B m() {
             System.out.println("Children class method");
             return new B();
       }
}

public class OverridingExample {
       public static void main(String args[]) {
             Super sup = new Super();
             sup.m();
             Children child = new Children();
             child.m();
       }
}

Output :  
Super class method
Child class method
Special Case: Can We Override Static Methods?
  • No. Static methods cannot be overridden.
  • ✅ A static method in a subclass with the same signature is considered method hiding, not overriding.
No, but we can declare a static method with the same signature in the subclass. It is not considered overriding, as there will be no runtime polymorphism. In this case, the method in the subclass hides the method in the superclass.

Example 1: Static Method Hiding

package com.tutorial4u;

class A {

       public static void m1() {

             System.out.println("method A");

       }

}

class B extends A {

       public static void m1() {

             System.out.println("method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

       }

} 


Output : 
method A
Note :  ๐Ÿ‘‰ If m1() was non-static, the output would be "method B" (runtime polymorphism).

Example 2: 

package com.tutorial4u;

class A {

       public static void m1() {

             System.out.println("method a1");

       }

       public void m2() {

             System.out.println("method a2");

       }

}

class B extends A {

       //Compilation Error: This instance method cannot override the static method from A

       public void m1() {

             System.out.println("method b1");

       }

       //Compilation Error: This static method cannot hide the instance method from A

       public static void m2() {

             System.out.println("method b2");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

             a.m2();

       }

}

Output : 

Compilation Error
This instance method cannot override the static method from A
This static method cannot hide the instance method from A

Important Points About Method Overriding

  • Private methods cannot be overridden (not inherited by subclasses).
  • Final methods cannot be overridden(not inherited by subclasses).
  • Static methods cannot be overridden (only hidden).
  • main() method cannot be overridden (because it’s static).
  • An overriding method cannot have a more restrictive access modifier.
  • Only instance methods can be overridden.

Sunday, 20 September 2015

To Check Prime Number

package com.tutorial4u;

import java.util.Scanner;

public class PrimeNumber {
       public static void main(String[] args) {
             int temp ;
             boolean isPrimeNumber = true;
             System.out.print("Please enter a number to check prime : ");
             Scanner sc = new Scanner(System.in);
             int num = sc.nextInt();
             for(int i=2;i<num/2;i++){
                    temp = num%i;
                    if(temp==0){
                           isPrimeNumber = false;
                           break;
                    }
             }
             if(isPrimeNumber){
                    System.out.println(num +" is Prime Number");
             }else{
                    System.out.println(num +" is not Prime Number");
             }
       }

}

Output:


Please enter a number to check prime : 23
23 is Prime Number

Palindrome Number



package com.tutorial4u;

import java.util.Scanner;

public class PalindromeNumber {
       public static void main(String[] args) {
             int num, reverse=0,temp;
             System.out.print("Please enter any number to check palindrome : ");
             Scanner sc = new Scanner(System.in);
             num = sc.nextInt();
            
             temp = num;
             while(num!=0){
                    reverse = reverse*10;
                    reverse=reverse+num%10;
                    num= num/10;
             }
             if(temp == reverse){
                    System.out.println("Given number is palindrome");
             }else{
                    System.out.println("Given number is not palindrome");
             }
       }

}

Output:

Please enter any number to check palindrome : 121

Given number is palindrome

Even Or Odd Number Without (%,/) Operator

package com.tutorial4u;

import java.util.Scanner;

public class EvenOrOdd {
       public static void main(String[] args) {
             System.out.print("Enter a num to check even or odd : ");
             Scanner sc = new Scanner(System.in);
             int num = sc.nextInt();
             if((num&1) == 0){
                    System.out.println("Given number is Even ");
             }else{
                    System.out.println("Given number is Odd");
             }
       }

}

Output: 

Enter a num to check even or odd : 34
Given number is Even 


Wednesday, 12 August 2015

Object and Class

Object and Class

OOPS (Object-Oriented Programming System) is a programming paradigm that solves problems by organizing code around objects, which represent real-world entities. It uses real-world concepts to model problems and solutions.

Main OOP Concepts:

  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

Class : 

A class is declared using the class keyword. It acts as a blueprint that defines the structure and behavior (data and methods) of objects. 

A class can contain:

  • Fields (variables)
  • Methods
  • Constructors
  • Blocks (static or instance)
  • Nested classes and interfaces
Syntax:

class ClassName {  
    // fields  
    // methods  
}                                

Object :

An object is an instance of a class that represents a real-world entity. It has three main characteristics:

  • State → represents data or properties of the object.
  • Behavior → represents functionality (methods) of the object.
  • Identity → represents a unique reference to the object in memory.

Ways to Create/Initialize an Object in Java :

1. Using new keyword

MyClass obj = new MyClass();   
2.Using Reflection (Class.forName(), getDeclaredConstructor().newInstance())

MyClass obj = (MyClass) Class.forName("MyClass").getDeclaredConstructor().newInstance();  

3.Using clone() method

MyClass obj2 = (MyClass) obj1.clone();   
4. Using Deserialization

(Object is recreated from a saved state).

For more details click ๐Ÿ‘‰here 

A class is initialized in Java when:

  1. An instance of the class is created using the new operator.
  2. A static method of the class is invoked.
  3. A static field of the class is accessed or assigned (unless it’s a compile-time constant).
  4. Reflection is used (e.g., Class.forName("MyClass")).
Example :

class MyClass {
    static {
        System.out.println("Class is being initialized!");
    }

    MyClass() {
        System.out.println("Constructor called: Object created");
    }

    static void staticMethod() {
        System.out.println("Static method called");
    }
}

public class TestInitialization {
    public static void main(String[] args) throws Exception {
        // Class initialization by creating object
        MyClass obj1 = new MyClass();

        // Class initialization by calling static method
        MyClass.staticMethod();

        // Class initialization using reflection
        MyClass obj2 = (MyClass) Class.forName("MyClass").getDeclaredConstructor().newInstance();
    }
} 
Output:


Class is being initialized! Constructor called: Object created Static method called Constructor called: Object created

Explanation:

  • The static block executes once when the class is initialized.
  • Class is initialized when an object is created, a static method is called, or using reflection.
  • Each new object triggers the constructor but does not re-run the static block.

Java Development Kit (JDK) and Java Runtime Environment (JRE)

                  Java Development Kit (JDK) and Java Runtime Environment (JRE)  To download and install the Java Development Kit (  JDK ) ...