Return: This
keyword is a keyword. This can be use with methods, loops, and statements. The
behavior of return is different with different scenarios.
1) Methods: Return
keyword is always used with method when the return type is not void. Return
type of methods could be anything. The return value must be as the return type
declared with method signature.
package com.demo;
public class DemoClass {
public String getName() {
String
name = "Try
Catch";
return name;
}
}
2) Loops: In
context of loops, return keyword used when we want to exit from loop. Here is
no need to declare return value.
package com.demo;
public class DemoClass {
public void getName() {
while (true) {
System.out.println("Try
Catch");
return;
}
}
}
Super: Super
is a keyword which is use to access the members of super or parent class. To
use super keyword, inheritance must be there. This keyword could use with
following statements:
package com.demo;
public class SuperClass {
String
name = "Instance
varibale of SuperClass";
public SuperClass() {
System.out.println("Super class
constructor...");
}
void getName(){
System.out.println("Method of
Super class...");
}
}
1) Instance Variables: Super
keyword use to access or call the instance variable of parent or super class
into child or base class.
2) Constructor: Using
super keyword, we can call the constructor of super class. You will see that,
while calling super class constructor there is () brackets. This is because;
constructor is also like a normal method. So to tell compiler that, we are
calling constructor not other members of super class, we have to use these
brackets.
3) Methods:
Methods of super call can be access using super keyword.
package com.demo;
public class BaseClass extends SuperClass {
String
name = "Try Catch";
public BaseClass() {
super();
}
public static void main(String[] args) {
BaseClass
base = new BaseClass();
base.getName();
base.showMethod();
}
void getName() {
System.out.println(super.name);
}
void showMethod() {
super.getName();
}
}
This: This
keyword is to use to call all the members of same class rather than super
class. Rest behavior is always same as super keyword.
package com.demo;
public class BaseClass extends SuperClass {
String
name = "Try
Catch";
public BaseClass() {
System.out.println("Basse class
constructor...");
}
public static void main(String[] args) {
BaseClass
base = new BaseClass();
base.getName();
base.showMethod();
}
void getName() {
System.out.println(this.name);
}
void showMethod() {
this.getName();
}
}
No comments:
Post a Comment
Thank you for your comments.