Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
Now Reading
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Variable hiding and variable shadowing in Java are two concepts that might look synonymous, but they have some minute differences. The two terms are used in varied contexts, and here is a tutorial that explains the two. This tutorial also addresses variable hiding and variable shadowing in Java with examples for different kinds of variables.
Java helps us declare variables within any method, class, or block. Variable shadowing and variable hiding in Java occur if two variables have the same name but varied scopes. Here, the values in the lesser class or inner scope override or shadow the superclass or outer scope values.
In Java, variables are defined within scopes, like a block, class, or method. When these defined variables have identical names to those defined in superclasses or outer scopes, the phenomenon is called shadowing. The phenomenon is called name masking when names are identical instead of variables.
If you have defined a variable in the subclass with the same name defined in the superclass, it is called variable hiding in Java. In this case, the superclass variables remain hidden by the subclass variables.
Method shadowing in Java is a phenomenon where methods are masked instead of variables. When you fill the same method in both subclass and superclass, including the parameters, the superclass method is shadowed by the subclass method. This mechanism is termed method shadowing.
Here’s an example demonstrating the concept:
class Superclass {
public static void display() {
System.out.println("This is the display method of the superclass");
}
}
class Subclass extends Superclass {
public static void display() {
System.out.println("This is the display method of the subclass");
}
}
public class MethodHiding {
public static void main(String[] args) {
MethodHiding obj = new MethodHiding();
Subclass.display();
}
}
Explanation:
Here in the given code, display () is the method name. It is described in both subclass and superclass, Subclass and Superclass, respectively. So, here if you use Subclass.display() command to call the display () method from the main (), the message thus printed will be “This is the display method of the subclass.”
When the various objects in a class share the same variable, it’s a static variable. Also, going by the term ‘class variable,’ you have to use the keyword ‘static’ to declare such a variable.
Here’s an example:
class Example {
static int instanceCount = 0;
public Example() {
instanceCount++;
}
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
Example obj3 = new Example();
System.out.println("Number of instances created: " + Example.instanceCount);
Example obj4 = new Example();
Example obj5 = new Example();
System.out.println("Number of instances created: " + Example.instanceCount);
}
}
Here, instanceCount is the static variable created to keep a tab on total example object creation.
Now that you’re clear with what static variables are let’s understand static variable hiding in Java with the help of this example:
class Parent {
static String parentID = "1";
static String parentName = "ParentClass";
public void displayName() {
System.out.println(parentName);
}
public void displayID() {
System.out.println(parentID);
}
}
class Child extends Parent {
static int childID = 2;
static String childName = "ChildClass";
@Override
public void displayName() {
System.out.println(childName);
}
@Override
public void displayID() {
System.out.println(childID);
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
parent.displayID();
parent.displayName();
child.displayID();
child.displayName();
}
Explanation:
The given code has the Parent class with parentID and parentName static variables. The Child class, which adds two more static variables, namely childID, and childName, is an extension of the Parent class. The Child class, which is the subclass, thus overrides the variables defined in the superclass Parent class because both classes have exactly the same named variables.
Instance variables, also termed non-static variables, are related to instances of a class. Thus, each class object has its own set of instance variables. These variables store unique data and are open to access and modification.
Instance variable hiding in Java with example is given here for you to understand the concept better:
class Counter {
int instanceCount = 0; // will get memory when instance is created
Counter() {
instanceCount++;
System.out.println(instanceCount);
}
public static void main(String args[]) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
}
}
Here instanceCount is the instance or the non-static variable. Now that you’re aware of what are non-static variables, here’s an example to understand variable hiding for non-static variables:
class Parent {
String parentName = "ParentClass";
public void displayName() {
System.out.println(parentName);
}
}
class Child extends Parent {
String childName = "ChildClass";
@Override
public void displayName() {
System.out.println(childName);
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
parent.displayName();
child.displayName();
}
}
Explanation:
In the given code, parentName is defined under the Parent class. childName is a variable defined under the Child class, an extension of the superclass Parent class. Since the two variables have been defined with the same name, the Child class variable masks the Parent class variable. Thus, when the displayName() method is called in the subclass Child class, it prints the name of the child and not the parent.
Much like the difference between method overriding and method shadowing in Java, there is a slight difference between variable hiding and method overriding. Method overriding is a phenomenon in Java where the methods defined are the same in the child and parent classes. Thus, the child class here masks the method implementation of the parent class.
Here’s an example for you to understand the differences better.
Variable hiding:
package com.kb.javainsimpleway.variable.hiding;
class Parent {
int parentX = 10;
static int parentY = 20;
}
class Child extends Parent {
int childX = 100;
static int childY = 200;
}
public class VariableHidingInheritance {
public static void main(String[] args) {
Child child = new Child();
System.out.println(child.childX);
System.out.println(child.childY);
}
}
Explanation:
In the given code are instance and static variables, namely parentX and parentY, respectively, in the Parent class. Child class, an extension of the Parent class, also has instance and static variables of similar names named childX and childY. Thus, here, the variables defined in the Child subclass demonstrate variable hiding, which masks the variables defined in the Parent superclass.
Method overriding:
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.displayInfo();
}
}
Explanation:
In the given code, displayInfo() is a method under the Animal superclass that prints the statement ‘I am an animal.’ The extension of the Animal class is the Dog class, including the dog1 variable, which overrules the displayInfo() method. This subclass possesses an implementation that prints ‘I am a dog.’ Thus, on the object dog1, if you call the displayInfo() method, it will print ‘I am a dog.’
Any instance variable is masked by the local variable in case they are defined with the same name. So, to access this shadowed variable, you have to use the keyword this. Here’s an example to make the concept clear:
class Student {
// instance variable
String studentName = "Tony Stark";
public void print() {
// local variable
String name = "Steve Rogers";
System.out.println(name); // prints local variable
System.out.println(this.studentName); // prints instance variable
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.print();
}
}
Explanation:
In this code, the variable studentName is defined in the Student class. This class has the print() method, where there is a variable defined as a name incorporating the value “Steve Rogers.” While giving the print command, this keyword is used, which specifically refers to the variable defined under the Student class.
If you have defined the subclass variable and superclass variable with the same name, the subclass variable will hide the superclass variable. So, if you want to access this superclass hidden variable, you must use the keyword super. If you’re wondering how to overcome instance variable hiding in Java, here’s an example to understand the concept:
class Parent {
String parentName = "ParentClass";
public void display() {
System.out.println(parentName);
}
}
class Child extends Parent {
String childName = "ChildClass";
@Override
public void display() {
System.out.println(childName);
System.out.println(super.parentName);
}
}
public class Main1 {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
Explanation:
This code has a superclass named Parent, which the subclass Child extends. Inside the superclass, the variable is named as parentName, and within the subclass, the variable is defined as childName. The definitions being the same, the subclass variable hides the superclass variable. However, the keyword super is used here for accessing the variable parentName, specifically with the command super.parentName.
You might need clarification on the two look-alike terms. But here are the key differences between the two.
Variable shadowing is a same-class phenomenon. It takes place between variables defined in a similar class. However, variable hiding occurs between a child class and its parent class.
When you keep the local variable name and instance variable name the same within one class, variable shadowing occurs. However, it is termed variable hiding when instance variables in parent and child classes are the same.
Being an effortless programming language, Java comes with a range of features. The simplicity of learning is first, followed by its platform independence. It is such a programming language that offers code reusability, and by learning it, you get one step closer to designing bug-free systems. It is also a robust programming language because of the sheer strength of its memory management and automated garbage collection. Thus, to kick-start your programming learning journey, Java can be the ideal first step.
1. What is variable shadowing in JavaScript?
In JavaScript, variable shadowing means local and global variables have the same names. Thus the global variable gets overshadowed by the local variable.
2. How to access the hidden and shadowed variables?
You can access the hidden and shadowed variables using specific keywords. this keyword is used to specifically mention the shadowed variable, while the super keyword is used to mention the hidden variable explicitly.
3. Is variable shadowing bad?
No, variable shadowing isn’t bad in all cases. It helps prevent accidental mistakes. With variable shadowing, you can avoid errors like unintended re-assigning of variable values.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...