0% found this document useful (0 votes)
6 views5 pages

Java "this" vs "super" Keyword Explained

The document explains the usage of 'this' and 'super' keywords in Java, providing examples of their application in class constructors and method calls. It also discusses the 'static' keyword, detailing its properties, memory management, and appropriate usage with variables, methods, and classes. Additionally, the document includes code examples demonstrating these concepts in practice.

Uploaded by

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

Java "this" vs "super" Keyword Explained

The document explains the usage of 'this' and 'super' keywords in Java, providing examples of their application in class constructors and method calls. It also discusses the 'static' keyword, detailing its properties, memory management, and appropriate usage with variables, methods, and classes. Additionally, the document includes code examples demonstrating these concepts in practice.

Uploaded by

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

this vs super keyword in java

===============================

Example1 of "this" keyword:


--------------------------

package [Link];

public class Person {

private int id;


private String name;
private String email;
private String pancard;
private int age;

public Person(int id, String name, String email, String pancard, int age) {

//calling constructor using "this" keyword


this(id,name,email);

/** "this" keyword is used to differentiate between


* local variable and instance variable if both are same .
*/
[Link] = pancard;
[Link] = age;

//calling method using "this" keyword


[Link]();

display();
}

public Person(int id, String name, String email) {

[Link] = id;
[Link] = name;
[Link] = email;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", email=" + email + ",
pancard=" + pancard + ", age=" + age
+ "]";
}

public void display() {


[Link]("Hello");
}

package [Link];

public class Test {


public static void main(String[] args) {
Person p1 = new Person(101, "Ravi", "ravi@[Link]","HJ7654RT",32);
[Link](p1);
}

Example2 of "super" keyword:


-----------------------------

package [Link];

class Car {
private String model;
private String color;
private String gearType;
private String carType;

String policy= "NA";

public Car(String model, String color, String gearType, String carType) {


[Link] = model;
[Link] = color;
[Link] = gearType;
[Link] = carType;
}

@Override
public String toString() {
return "Car [model=" + model + ", color=" + color + ", gearType=" +
gearType + ", carType=" + carType + "]";
}

class Dzire extends Car {

private String flyingQuality;


String policy = "6 months locking";

public Dzire(String model, String color, String gearType, String carType,


String flyingQuality) {
super(model, color, gearType, carType);
[Link] = flyingQuality;
}

@Override
public String toString() {
[Link](policy);
[Link]([Link]);
return [Link]()+"Dzire [flyingQuality=" + flyingQuality + "]";
}

public class Test2 {

public static void main(String[] args) {


Dzire car1 = new Dzire("Dzire2024", "White", "Manual","Sedan","Dzire
car can fly");
[Link]([Link]());

Use of "static" keyword in java


------------------------------

When to use static keyword?


---------------------------
Aquaguard -> static
collegeName-> static

About static :

1. Static is property of class not object.


2. Static variable initialized in seperate area called "static context" in heap
memory area.
It initialized only once during class initialization.
3. Static variables can be accessed by its class name, we can also access static
properties while using object but access of static properties using class name is
preferable.
4. Static variable and not static variable, can be access inside any not-static
methods directly.
5. We can't access not static variable within the static block or static method
because not static variable is property
of object not class. keep in mind that static properties loaded first before
instance of object creation.

-> JVM is responsible to do memory management in java. There are 5 types of memory
which is used to load and run java program.
1. Heap area -> All the instances or object are created in heap area
2. stack area -> All the references and local primitive variables
3. class area ot method area
4. program counter
5. Native area

Is "static" keyword can be used with the followings?


----------------------------------------------------
variable -> Yes
method -> Yes
Constructor -> No
class -> static can be used with inner class but can not be used with concrete
class

Ex1
----

package [Link];

public class Student {


private String name;
private int rollNum;

public static String collegeName = "YTIET";

public Student(String name, int rollNum) {


[Link] = name;
[Link] = rollNum;
}

public void show() {


[Link]("Name: "+name+" Roll Number: "+rollNum+" College
Name:"+collegeName);
}

public static void main(String[] args) {


Student s1 = new Student("Raj", 101);
Student s2 = new Student("Nikita", 102);
Student s3 = new Student("Keshav", 103);
Student s4 = new Student("Raju", 104);

[Link]();
//[Link](name);
[Link]([Link]);
//[Link]([Link]);
[Link](collegeName);
[Link]([Link]);
[Link]([Link]);

Ex2
----

package [Link];

public class Student {


private String name;
private int rollNum;

public static String collegeName = "YTIET";

public Student(String name, int rollNum) {


[Link] = name;
[Link] = rollNum;
}
public void show() {
[Link](rollNum);
[Link](collegeName);
[Link]("Name: "+name+" Roll Number: "+rollNum+" College
Name:"+collegeName);
}

static void display() {


[Link]("display() method...");
//[Link](rollNum);
[Link](collegeName);
Student s = new Student("abc", 200);
[Link]([Link]);
}

package [Link];

public class Test3 {

public static void main(String[] args) {


Student s1 = new Student("Raj", 101);

[Link]();
//[Link](name);
//[Link]([Link]);
//[Link]([Link]);
//[Link](collegeName);
[Link]([Link]);
[Link]([Link]);
[Link]();
}

Common questions

Powered by AI

Using static properties in object-oriented design can challenge encapsulation and abstraction as these properties are linked to the class rather than individual objects. This shared nature can lead to broader access beyond typical encapsulation boundaries, which might expose internal states contrary to precise encapsulation. Furthermore, while abstraction allows object variations to uniquely encapsulate data, static elements unchangeably abstract functionality to maintain a consistent state across all instances, limiting the diversity intended in true object encapsulation .

In Java, the 'this' keyword serves to differentiate between local and instance variables when they have the same name. It allows for clear reference to the instance variable. For example, in the Person class, 'this(id, name, email)' calls the constructor of the same class, using 'this' to direct the flow to the right constructor. Furthermore, 'this.display()' and 'display()' demonstrate method invocation within the class, showing how even without 'this', the method from the current class can be called. Thus, 'this' ensures clarity in variable references and facilitates method invocation within the class .

Java uses several distinct memory areas for memory management, namely the Heap area, Stack area, Class area or Method area, Program Counter, and Native area. The Heap area is where objects are instantiated. The Stack area holds references and local primitive variables. The Class area contains class-level data like static variables and methods. The Program Counter tracks the execution address of the current thread. Lastly, the Native area is used for native methods. Together, these areas ensure that Java efficiently manages memory allocation, execution flow, and method handling .

The 'super' keyword in Java plays a crucial role in method overriding by providing a way to explicitly access a method from a superclass that has been overridden in a subclass. This allows a subclass to enhance or modify the behavior of inherited methods while still being able to call and leverage the superclass's original method functionality. When a class overrides a method, using 'super.methodName()' calls the version in the parent class, thus offering flexibility and layered method functionalities in a hierarchical class structure .

The 'super' keyword in Java is used to access methods and variables from a superclass. It allows an object to call the parent's constructor, methods, or to access the parent's variables when overridden or shadowed by child class members. For instance, in the Dzire class extending Car, 'super(model, color, gearType, carType)' calls the Car constructor, and 'super.policy' accesses the policy variable from Car even though Dzire also defines a 'policy' variable. This ensures that specific behaviors or properties of the parent class can be utilized or referenced directly .

Static variables in Java are initialized in a distinct memory area known as the "static context," which is part of the class area in heap memory. They are initialized only once during class loading, not upon object creation. Thus, static variables are shared across all instances of a class. Because they are class-level variables, these static variables are accessible via the class name itself rather than a specific instance, which emphasizes their global availability during the entire life of the application .

Static methods differ from instance methods in that they belong to the class rather than any object instance. Consequently, they can access static variables directly but cannot directly access instance variables unless an object reference is used. Static methods are called using the class name, which helps in situations where a function shares common logic across instances. This contrasts with instance methods, which can freely access all class properties, static or non-static, since they operate in the context of a specific object .

The Java Virtual Machine (JVM) manages memory by dividing it into areas like Heap and Class area (also known as Method area). Object instances are created in the Heap area, where each instance maintains its own specific data. Conversely, static elements are stored in the Class area, being loaded during the class's load phase. They are shared among all instances of that class. The JVM ensures that while each object can have varied states, static elements remain consistent across all instances, enabling shared data without redundancy .

The 'static' keyword can apply to variables and methods because they belong to the class, not instances. Static qualities are shared across all instances of a class and initialized once when the class is loaded. However, constructors are inherently designed to initialize individual objects, creating a unique instance each time they're called. Since the purpose of a static member conflicts with the nature of a constructor, which is to handle object creation at an instance level, there is no logical application for 'static' with constructors .

Static methods in Java are restricted to accessing only static properties directly. This is because static members belong to the class and are initialized during class loading. Static methods cannot access non-static members directly since they are object-specific properties, only initialized when an instance of the class is created. Accessing non-static properties within a static method requires creating an instance of the class or passing an instance as a parameter, ensuring the context is aligned with the object-specific nature of non-static properties .

You might also like