Monday, 10 February 2014

Access-Specifier and Method overriding

We have 4 access-specifier.The following sequence represents the heirarchy from weakest/less restrictive access specifier to strongest/more restrictive access specifier
  • public
  • protected
  • no-access or default
  • private
If super class method is public,while overriding it in child class,it should be public,Since it is the weakest access specifier or least restrictive access specifier


OverrideTest.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo
{
    public void sayHello()
    {
        System.out.println("Demo:sayHello()");
    }
}
 
public class OverrideTest extends Demo
{
    public void sayHello()//cannot be declared private,protected,no access
    {
        System.out.println("OverrideTest:sayHello()");
    }
}
If super class method is protected,while overriding it in child class,it can be public or protected but not anything else
OverrideTest.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo
{
 protected void sayHello()
 {
  System.out.println("Demo:sayHello()");
 }
}
 
public class OverrideTest extends Demo
{
 public void sayHello()//can be public,protected But not anything else
 {
  System.out.println("OverrideTest:sayHello()");
 }
}
 If superclass method is default,then while overriding it in child class,it can be public,protected or no access,but cannot be private.
 OverrideTest.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo
{
 void sayHello() //default access specifier
 {
  System.out.println("Demo:sayHello()");
 }
}
 
public class OverrideTest extends Demo
{
 protected void sayHello()//can be public,protected,default But not private
 {
  System.out.println("OverrideTest:sayHello()");
 }
}


 If superclass method is private,then while overriding it in child class,it can be anything. Since private method cannot be overrided.
OverrideTest.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo
{
 private void sayHello() //cannot be overrided
 {
  System.out.println("Demo:sayHello()");
 }
}
 
public class OverrideTest extends Demo
{
 public void sayHello()//this is separate method,which can be overrided later by its subclass
 {
  System.out.println("OverrideTest:sayHello()");
 }
}

No comments:

Post a Comment