0% found this document useful (0 votes)
7 views15 pages

Java Notes

The document explains the usage of the 'this' and 'super' keywords in Java, detailing their roles in referencing current objects and parent class objects, respectively. It also covers parameter passing techniques, including call by value and call by reference, alongside method overriding principles and rules. Examples are provided to illustrate these concepts in practical Java code.

Uploaded by

Gagandeep Chawla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Java Notes

The document explains the usage of the 'this' and 'super' keywords in Java, detailing their roles in referencing current objects and parent class objects, respectively. It also covers parameter passing techniques, including call by value and call by reference, alongside method overriding principles and rules. Examples are provided to illustrate these concepts in practical Java code.

Uploaded by

Gagandeep Chawla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

THIS Keyword in Java with Example

Keyword THIS is a reference variable in Java that refers to the current object.

The various usages of 'THIS' keyword in Java are as follows:

It can be used to refer instance variable of current class

It can be used to invoke or initiate current class constructor

It can be passed as an argument in the method call

It can be passed as argument in the constructor call

It can be used to return the current class instance

Example of this
Super Keyword in Java

The super keyword in java is a reference variable that is used to refer parent class objects. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:

1. Use of super with variables: This scenario occurs when a derived class and base class has
same data members. In that case there is a possibility of ambiguity for the JVM. We can
understand it more clearly using this code snippet:

Base class vehicle */

class Vehicle

int maxSpeed = 120;

/* sub class Car extending vehicle */

class Car extends Vehicle

int maxSpeed = 180;

void display()

/* print maxSpeed of base class (vehicle) */

[Link]("Maximum Speed: " + [Link]);

}
/* Driver program to test */

class Test

public static void main(String[] args)

Car small = new Car();

[Link]();

2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we use
super keyword. This code snippet helps to understand the said usage of super keyword.

/* Base class Person */

class Person

void message()

[Link]("This is person class");

/* Subclass Student */

class Student extends Person

void message()
{

[Link]("This is student class");

// Note that display() is only in Student class

void display()

// will invoke or call current class message() method

message();

// will invoke or call parent class message() method

[Link]();

/* Driver program to test */

class Test

public static void main(String args[])

Student s = new Student();

// calling display() of Student

[Link]();
}

Output:

This is student class

This is person class

In the above example, we have seen that if we only call method message() then, the current
class message() is invoked but with the use of super keyword, message() of superclass could
also be invoked.

3. Use of super with constructors: super keyword can also be used to access the parent class
constructor. One more important thing is that, ‘’super’ can call both parametric as well as non
parametric constructors depending upon the situation. Following is the code snippet to explain
the above concept:

/* superclass Person */

class Person

Person()

[Link]("Person class Constructor");

/* subclass Student extending the Person class */

class Student extends Person

Student()
{

// invoke or call parent class constructor

super();

[Link]("Student class Constructor");

/* Driver program to test*/

class Test

public static void main(String[] args)

Student s = new Student();

Output:

Person class Constructor

Student class Constructor

In the above example we have called the superclass constructor using keyword ‘super’ via
subclass constructor.

Other Important points:

Call to super() must be first statement in Derived(Student) Class constructor.


If a constructor does not explicitly invoke a superclass constructor, the Java compiler
automatically inserts a call to the no-argument constructor of the superclass. If the superclass
does not have a no-argument constructor, you will get a compile-time error. Object does have
such a constructor, so if Object is the only superclass, there is no problem.

If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly,


you might think that a whole chain of constructors called, all the way back to the constructor of
Object. This, in fact, is the case. It is called constructor chaining.

Parameter Passing Techniques in Java with Examples

There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are called
formal arguments.

Types of parameters:

Formal Parameter : A variable and its type as they appear in the prototype of the function or
method.

Syntax:

function_name(datatype variable_name)

Actual Parameter : The variable or expression corresponding to a formal parameter that


appears in the function or method call in the calling environment.

Syntax:

func_name(variable name(s));

Important methods of Parameter Passing

Pass By Value: Changes made to formal parameter do not get transmitted back to the caller.
Any modifications to the formal parameter variable inside the called function or method affect
only the separate storage location and will not be reflected in the actual parameter in the
calling environment. This method is also called as call by value.

Java in fact is strictly call by value.


Example:

// Java program to illustrate

// Call by Value

// Callee

class CallByValue {

// Function to change the value

// of the parameters

public static void Example(int x, int y)

x++;

y++;

// Caller

public class Main {

public static void main(String[] args)

int a = 10;

int b = 20;
// Instance of class is created

CallByValue object = new CallByValue();

[Link]("Value of a: " + a

+ " & b: " + b);

// Passing variables in the class function

[Link](a, b);

// Displaying values after

// calling the function

[Link]("Value of a: "

+ a + " & b: " + b);

Output:

Value of a: 10 & b: 20

Value of a: 10 & b: 20

Shortcomings:

Inefficiency in storage allocation

For objects and arrays, the copy semantics are costly

Call by reference(aliasing): Changes made to formal parameter do get transmitted back to the
caller through parameter passing. Any changes to the formal parameter are reflected in the
actual parameter in the calling environment as formal parameter receives a reference (or
pointer) to the actual data. This method is also called as <em>call by reference. This method is
efficient in both time and space.

// Java program to illustrate

// Call by Reference

// Callee

class CallByReference {

int a, b;

// Function to assign the value

// to the class variables

CallByReference(int x, int y)

a = x;

b = y;

// Changing the values of class variables

void ChangeValue(CallByReference obj)

obj.a += 10;

obj.b += 20;

// Caller

public class Main {


public static void main(String[] args)

// Instance of class is created

// and value is assigned using constructor

CallByReference object

= new CallByReference(10, 20);

[Link]("Value of a: "

+ object.a

+ " & b: "

+ object.b);

// Changing values in class function

[Link](object);

// Displaying values

// after calling the function

[Link]("Value of a: "

+ object.a

+ " & b: "

+ object.b);

}
}

Output:

Value of a: 10 & b: 20

Value of a: 20 & b: 40

Please note that when we pass a reference, a new reference variable to the same object is
created. So we can only change members of the object whose reference is passed. We cannot
change the reference to refer to some other object as the received reference is a copy of the
original reference.

Method Overriding in Java

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.

overriding in java

Method overriding is one of the way by which java achieve Run Time [Link] version
of a method that is executed will be determined by the object that is used to invoke it. If an
object of a parent class is used to invoke the method, then the version in the parent class will
be executed, but if an object of the subclass is used to invoke the method, then the version in
the child class will be executed. In other words, it is the type of the object being referred to (not
the type of the reference variable) that determines which version of an overridden method will
be executed.

// A Simple Java program to demonstrate

// method overriding in java

// Base Class

class Parent {

void show()

{
[Link]("Parent's show()");

// Inherited class

class Child extends Parent {

// This method overrides show() of Parent

@Override

void show()

[Link]("Child's show()");

// Driver class

class Main {

public static void main(String[] args)

// If a Parent type reference refers

// to a Parent object, then Parent's

// show is called

Parent obj1 = new Parent();

[Link]();
// If a Parent type reference refers

// to a Child object Child's show()

// is called. This is called RUN TIME

// POLYMORPHISM.

Parent obj2 = new Child();

[Link]();

Output:

Parent's show()

Child's show()

Rules for method overriding:

 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.

 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 .

 overridden method is final

 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.

 Private methods can not be overridden : Private methods cannot be overridden as they
are bonded during compile time. Therefore we can’t even override private methods in a
subclass.(See this for details).

 The overriding method must have same return type (or subtype) : From Java 5.0
onwards it is possible to have different return type for a overriding method in child
class, but child’s return type should be sub-type of parent’s return type. This
phenomena is known as covariant return type.

 Invoking overridden method from sub-class : We can call parent class method in
overriding method using super keyword.

 Overriding and abstract method: Abstract methods in an interface or abstract class are
meant to be overridden in derived concrete classes otherwise a compile-time error will
be thrown.

 Overriding and synchronized/strictfp method : The presence of synchronized/strictfp


modifier with method have no effect on the rules of overriding, i.e. it’s possible that a
synchronized/strictfp method can override a non synchronized/strictfp one and vice-
versa.

Overriding vs Overloading :

Overloading is about same method have different signatures. Overriding is about same method,
same signature but different classes connected through inheritance.

OverridingVsOverloading

Overloading is an example of compiler-time polymorphism and overriding is an example of run


time polymorphism.

You might also like