[go: up one dir, main page]

0% found this document useful (0 votes)
2 views75 pages

m2 java

The document provides an overview of Java classes and objects, explaining the concepts of classes as blueprints for creating objects and objects as instances of classes. It covers the syntax for defining classes, the role of instance variables, methods, constructors, and the use of the 'new' keyword for memory allocation. Additionally, it discusses the types of constructors, the 'this' keyword, and access modifiers in Java.

Uploaded by

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

m2 java

The document provides an overview of Java classes and objects, explaining the concepts of classes as blueprints for creating objects and objects as instances of classes. It covers the syntax for defining classes, the role of instance variables, methods, constructors, and the use of the 'new' keyword for memory allocation. Additionally, it discusses the types of constructors, the 'this' keyword, and access modifiers in Java.

Uploaded by

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

MODULE -2

Java Classes and Objects


Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class public class Main {


To create a class, int x = 5;
use the keyword class:
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
What is an object in Java
object in Java
An entity that has state and behavior is known as an object e.g.,
chair, bike, marker, pen, table, car, etc. It can be physical or
logical (tangible and intangible).
The example of an intangible object is the banking system.

An object is an instance of a class. A


class is a template or blueprint from which
objects are created. So, an object is the
instance(result) of a class.
Object Definitions:
•An object is a real-world entity.
•An object is a runtime entity.
•The object is an entity which has state
and behavior.
•The object is an instance of a class.
What is a class in Java
A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.

A class in Java can contain:

• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as an instance variable.

Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method
Code Reusability
Code Optimization
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
//Creating an object or instance

Student s1=new Student();//creating an object of Student


System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better approach than previous one.
Let's see a simple example, where we are having main() method in another class.
3 Ways to initialize object
There are 3 ways to initialize object in Java. class Student{
int id;
• By reference variable String name;
• By method }
• By constructor class TestStudent2{
public static void main(String args[]){
1)Object and Class Example: Student s1=new Student();
Initialization through reference s1.id=101;
Initializing an object means storing data into the
object. Let's see a simple example where we are s1.name="Sonoo";
going to initialize the object through a reference System.out.println(s1.id+"
variable.
"+s1.name);//printing members with
File: TestStudent2.java
a white space
}
}
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the
insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
class Employee{
3) Object and Class Example: int id;
Initialization through a constructor String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
//Java Program to demonstrate the working of a banking-system
class Account{ void checkBalance(){System.out.println("Balance is:
int acc_no; "+amount);}
String name;
float amount; void display(){System.out.println(acc_no+" "+name+"
void insert(int a,String n,float amt){ "+amount);}
acc_no=a; }
name=n; //Creating a test class to deposit and withdraw amount
amount=amt; class TestAccount{
} public static void main(String[] args){
Account a1=new Account();
void deposit(float amt){ a1.insert(832345,"Ankit",1000);
amount=amount+amt; a1.display();
System.out.println(amt+" deposited"); a1.checkBalance();
} a1.deposit(40000);
a1.checkBalance();
void withdraw(float amt){ a1.withdraw(15000);
if(amount<amt){ a1.checkBalance();
System.out.println("Insufficient Balance"); }}
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
Constructors in Java
1.Types of constructors
1.Default Constructor
2.Parameterized Constructor
2.Constructor Overloading
3.Does constructor return any value?
In Java, a constructor is a block of codes similar to the
method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to initialize the
object.
Every time an object is created using the new() keyword, at
least one constructor is called.
It calls a default constructor if there is no constructor
There are two types of constructors in Java: no-arg constructor, and parameterized
available
constructor.
in the class. In such case, Java compiler provides a
default
Note: It isconstructor by default.
called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
Rules for creating Java constructor
There are two rules defined for the constructor.
1.Constructor name must be the same as its class name
2.A Constructor must have no explicit return type
3.A Java constructor cannot be abstract, static, final, and
synchronized
Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
Example of default constructor class Bike1{

Bike1(){System.out.println("Bike is created");}

public static void main(String args[]){


//calling a default constructor
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of a default constructor?


The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
Example of default constructor that displays the default values
class Student3{

int id;
String name;
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

Student3 s1=new Student3();


Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Java Parameterized Constructor

A constructor which has a specific number of parameters is called a


parameterized constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in
the list and their types.
Constructor Overloading in Java//Java program to overload constructors
class Student5{
int id;
String name;
int age;

Student5(int i,String n){


id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object
to another like copy constructor in C++.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Copying values without constructor
We can copy the values of one object into another by assigning the objects
values to another object. In this case, there is no need to create the
constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
this keyword in Java
There can be a lot of usage of Java this keyword.
In Java, this is a reference variable that refers
to the current object. //WAP to use this pointer in C++
#include<iostream>
class Test
{
private:
int x;
public:
void setX (int x)
{
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If
there is ambiguity between the instance variables and formal arguments, this
keyword resolves the problem of ambiguity.
class Student{
int rollno; //Instance variables
String name;
float fee;
Student(int rollno,String name,float fee){ //local variables or formal arguments
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f); In the above example, parameters (formal
s1.display(); arguments) and instance variables are same.
s2.display(); So, we are using this keyword to
distinguish local variable and instance
}}
Solution of the above problem by this
keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method.
class A{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

class A{
A()
{
System.out.println("hello a");
}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Calling parameterized constructor from default
constructor:

class A{
A()
{
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining.
class Student{
int rollno;
Student(int rollno,String name,String course,float fee){
String name,course;
this.fee=fee;
float fee;
this(rollno,name,course);//Compile Time Error
Student(int rollno,String name,String course){
}
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
Question1

class Main {
public static void main(String args[]) {
int t;
System.out.println(t);
}
}
Access Modifiers in Java
1.Private access modifier
2.Default access modifier
3.Protected access modifier
4.Public access modifier
There are two types of modifiers in Java: access modifiers and non-access
modifiers.
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1.Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2.Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3.Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4.Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
There are many non-access modifiers, such as static, abstract, synchronized,
native, volatile, transient
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or
a class. It is used to restrict a user in Java.
The following are different contexts where the final is used:
1.Variable
2.Method
3.Class
Characteristics of final keyword in Java:
In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or
extended. Here are some of its characteristics:
•Final variables: When a variable is declared as final, its value cannot be changed once it has been
initialized. This is useful for declaring constants or other values that should not be modified.
•Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is
useful for methods that are part of a class’s public API and should not be modified by subclasses.
•Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for
classes that are intended to be used as is and should not be modified or extended.
•Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class. This ensures that the value of the variable is set and cannot be changed.
•Performance: The use of a final can sometimes improve performance, as the compiler can optimize
the code more effectively when it knows that a variable or method cannot be changed.
•Security: The final can help improve security by preventing malicious code from modifying sensitive
data or behavior.
Overall, the final keyword is a useful tool for improving code quality and ensuring that certain
aspects of a program cannot be modified or extended. By declaring variables, methods, and classes
as final, developers can write more secure, robust, and maintainable code.
Java Final Variable
When a variable is declared with the final keyword, its value can’t be changed, essentially, a constant. This also
means that you must initialize a final variable.
It is good practice to represent final variables in all uppercase, using underscore to separate words.

public class ConstantExample {


public static void main(String[] args) {

final double PI = 3.14159;

System.out.println("Value of PI: " + PI);


}
}
Different Methods of Using Final Variable
1. final Variable

final int THRESHOLD = 5;

2. Static final Variable

static final double PI = 3.141592653589793;

3. Static Blank final Variable

static final double PI;

Initializing a final Variable


We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A
final variable can only be initialized once, either via an initializer or an assignment statement.
Q 1: When to use a final variable?

The only difference between a normal variable and a final variable is that we can re-assign
the value to a normal variable but we cannot change the value of a final variable once
assigned. Hence final variables must be used only for the values that we want to remain
constant throughout the execution of the program.
2) Java final method
If you make any method as final,
you cannot override it.

class Bike{
final void run()
{
System.out.println("running");}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with
100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
3) Java final class
If you make any class as final, you cannot extend it.

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Java instanceof Operator
The instanceof operator in Java is used to check whether an object is an instance of a particular
class or not.
class Main {
Its syntax is
public static void main(String[] args) {
objectName instanceOf className;
String name = “Hello";
boolean result1 = name instanceof String;
System.out.println("name is an instance of
String: " + result1);

Main obj = new Main();


boolean result2 = obj instanceof Main;
System.out.println("obj is an instance of
Main: " + result2);
}
}
Java instanceof during Inheritance
class Animal {
}

class Dog extends Animal {


}

class Main {
public static void main(String[] args) {

Dog d1 = new Dog();

System.out.println(d1 instanceof Dog); // prints true


System.out.println(d1 instanceof Animal); // prints true
}
}
Java instanceof in Interface

interface Animal {
}

class Dog implements Animal {


}

class Main {
public static void main(String[] args) {

Dog d1 = new Dog();


System.out.println(d1 instanceof Animal); //returns true
}
}
Inheritance in Java
1.Inheritance
2.Types of Inheritance
3.Why multiple inheritance is not possible in Java in case of class?
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new methods
and fields in your current class also.
Why use inheritance in java
•For Method Overriding (so runtime polymorphism can be achieved).
•For Code Reusability.
Terms used in Inheritance

•Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
•Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
•Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
•Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the previous
class.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or
superclass, and the new class is called child or subclass.
Types of inheritance in java
On the basis of class, there can be three types of
inheritance in java:
 single
 Multilevel
 hierarchical
In java programming, multiple and hybrid
inheritance is supported through interface only.

Programmer IS-A Employee. It


means that Programmer is a type of
Employee.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void
msg(){System.out.println("Welcome");}
}
class C extends A,B{

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method
would be invoked?
}
}
Compile Time Error
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent
class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class
‘B’ inherits all the properties of the class ‘A’.
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One {


public void print_for() { System.out.println("for"); }
}
public class Main {
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
2. Multilevel Inheritance class One {
In Multilevel Inheritance, a derived class will be public void print_geek() {
inheriting a base class, and as well as the derived System.out.println("Geeks");
class also acts as the base class for other classes. In }
the below image, class A serves as a base class for }
the derived class B, which in turn serves as a base class Two extends One {
class for the derived class C. In Java, a class cannot public void print_for() {
directly access the grandparent’s members. System.out.println("for");
}
}
class Three extends Two {
public void print_lastgeek() {
System.out.println("Geeks");
}
}
public class Main {
public static void main(String[] args) {
Three g = new Three();
g.print_geek();
g.print_for();
g.print_lastgeek();
}
}
// concept of Hierarchical inheritance

class A { public class Test {


public void print_A() { System.out.println("Class A"); } public static void main(String[] args)
} {
class B extends A { B obj_B = new B();
public void print_B() { System.out.println("Class B"); } obj_B.print_A();
} obj_B.print_B();
class C extends A {
public void print_C() { System.out.println("Class C"); } C obj_C = new C();
} obj_C.print_A();
class D extends A { obj_C.print_C();
public void print_D() { System.out.println("Class D"); }
} D obj_D = new D();
obj_D.print_A();
obj_D.print_D();
}
}
interface One {
public void print_geek(); // Drived class
} public class Main {
public static void main(String[] args)
interface Two {
public void print_for(); {
} Child c = new Child();
c.print_geek();
interface Three extends One, Two {
public void print_geek(); c.print_for();
} c.print_geek();
class Child implements Three { }
@Override public void print_geek()
{ }
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}
What is Abstraction
Abstraction in Java, which is one of the OOPs concepts, is the process of showing only the required information to the
user by hiding other details. For example, consider a mobile phone, we just know that pressing on the call button, will
dial the required number. But we actually don’t know the actual implementation of how a call works. This is because the
internal mechanism is not visible to us. This is a real example of abstraction. Similarly, abstraction works in the same
way in Object-oriented programming. In this tutorial, we will learn how to achieve abstraction using Java abstract
classes and methods.
Use of Abstraction
•Provides security by hiding implementation details.
•Provides flexibility for the subclass to implement the functionality of the inherited abstract method of the superclass.

Realtime Examples of Abstraction in Java


1. Let’s first take ATM machine as a real-time example. We all use an ATM machine for cash withdrawal, money transfer,
retrieve min-statement, etc. in our daily life.

But we don’t know internally what things are happening inside ATM machine when you insert an ATM card for performing
any kind of operation.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


•Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
•Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1.The method must have the same name as in the parent class
2.The method must have the same parameter as in the parent class.
3.There must be an IS-A relationship (inheritance).
//Java Program to demonstrate the real scenario of Java Method Overriding
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class when we’re working with
objects. You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.
Use of super keyword in Java

1. Use of super with Variables


2. Use of super with Methods
3. Use of super with Constructors
Characteristics of Super Keyword in Java
In Java, super keyword is used to refer to the parent class of a subclass. Here are
some of its key characteristics:
•super is used to call a superclass constructor: When a subclass is created, its
constructor must call the constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the parent class.
•super is used to call a superclass method: A subclass can call a method defined
in its parent class using the super keyword. This is useful when the subclass wants
to invoke the parent class’s implementation of the method in addition to its own.
•super is used to access a superclass field: A subclass can access a field defined
in its parent class using the super keyword. This is useful when the subclass wants
to reference the parent class’s version of a field.
•super must be the first statement in a constructor: When calling a superclass
constructor, the super() statement must be the first statement in the constructor of
the subclass.
•super cannot be used in a static context: The super keyword cannot be used in
a static context, such as in a static method or a static variable initializer.
1. Use of super with Variables

// super keyword in java example

class Vehicle {
int maxSpeed = 120;
}
class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
System.out.println("Maximum Speed: "+ super.maxSpeed);
// System.out.println("Maximum Speed: "+maxSpeed);
}
}
class Test {
public static void main(String[] args)
{
Car obj = new Car();
obj.display();
}
}
2. Use of super with Methods
This is used when we want to call the parent class method. So whenever a parent and child class have the same-
named methods then to resolve ambiguity we use the super keyword.
class Person { class Test {
void message() public static void main(String args[])
{
System.out.println("This is person class\n");
{
} Student s = new Student();
} s.display();
class Student extends Person { }
void message() }
{
System.out.println("This is student class");
}
void display()
{
message();
super.message();
}
}
3. Use of super with constructors
The 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 on the situation.
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
class Student extends Person {
Student()
{
super();
System.out.println("Student class Constructor");
}
}
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Abstraction in Java is the process in which we only show essential details/functionality to the user. The
non-essential implementation details are not displayed to the user.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java
1.Abstract class (0 to 100%)
2.Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to
be extended and its method implemented. It cannot be instantiated.
abstract class Bank{
abstract int getRateOfInterest();
}

class SBI extends Bank{


int getRateOfInterest(){return 7;}
}

class PNB extends Bank{


int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){

Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}

}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}

class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable()
d.draw();

}}

You might also like