m2 java
m2 java
• 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
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");}
int id;
String name;
void display(){System.out.println(id+" "+name);}
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.
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.
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.
class Main {
public static void main(String[] args) {
interface Animal {
}
class Main {
public static void main(String[] args) {
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.
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.
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.
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();
}}