Skip to content

Commit e02c68b

Browse files
authored
Merge pull request cherryWood55#7 from Uwanthi/master
Create Overriding in java.txt
2 parents d9bc11a + 4673c3e commit e02c68b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Overriding in java.txt

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Overriding in Java
2+
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
3+
4+
Rules for method overriding:
5+
6+
1.Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.
7+
8+
2.Final methods can not be overridden : If we don�t want a method to be overridden, we declare it as final. Please see Using final with Inheritance .
9+
10+
3.Static methods can not be overridden(Method Overriding vs Method Hiding) : When you defines a static method with same signature as a static method in base class, it is known as method hiding.
11+
The following table summarizes what happens when you define a method with the same signature as a method in a super-class.
12+
13+
A simple example for overriding:
14+
// Base Class
15+
class Parent {
16+
void show()
17+
{
18+
System.out.println("Parent's show()");
19+
}
20+
}
21+
22+
// Inherited class
23+
class Child extends Parent {
24+
// This method overrides show() of Parent
25+
@Override
26+
void show()
27+
{
28+
System.out.println("Child's show()");
29+
}
30+
}
31+
32+
// Driver class
33+
class Main {
34+
public static void main(String[] args)
35+
{
36+
// If a Parent type reference refers
37+
// to a Parent object, then Parent's
38+
// show is called
39+
Parent obj1 = new Parent();
40+
obj1.show();
41+
42+
// If a Parent type reference refers
43+
// to a Child object Child's show()
44+
// is called. This is called RUN TIME
45+
// POLYMORPHISM.
46+
Parent obj2 = new Child();
47+
obj2.show();
48+
}
49+
}

0 commit comments

Comments
 (0)