Chapter2_Notes java
Chapter2_Notes java
Static Members
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
static variable
If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
The static variable gets memory only once.
static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an object of a class (i.e
classname.methodName( )).
A static method can access static data member and can change the value of it.
static block
Is used to initialize the static data member.
It is executed before the main method at the time of class loading
Example:
class Student
{
int rollno;//instance variable
String name; //instance variable
static String college ="KLE";//static variable
//constructor
Student(int rollno, String name)
{
this.rollno=rollno;
this.name = name;
}
Inheritance
Inheritance 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).
Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
Inheritance allows the subclasses to inherit the properties (variables) and behavior
(methods) if its parent class and also have its properties and behavior
Advantages of inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
The syntax of Java Inheritance
class Super
{
.....
.....
}
class Sub extends Super {
.....
.....
}
The extends keyword indicates that you are making a new class that is derived from an
existing class.
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: Super class is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Types of inheritance in java
On the basis of class, there are four types of inheritance in java:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
1. Single Inheritance
In single inheritance, a single subclass extends from a single super class.
2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a super class and then the same subclass acts
as a super class for another class
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single super class.
4. Multiple Inheritance
In multiple inheritance a single subclass extends from multiple super classes
Super Keyword
The super keyword is a reference variable which is used to refer immediate parent class object.
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
Example:
class Vehicle
{
String name;
int regNo;
double cost;
int speed=70;
Vehicle(String name,int regNo,double cost)
{
this.name=name;
this.regNo=regNo;
this.cost=cost;
}
public void display()
{
System.out.println("Name::"+name+"Reg
No::"+regNo+"Cost::"+cost);
}
}
class Car extends Vehicle
{
Car(String name,int regNo,double cost)
{
super(name,regNo,cost);//Calling super class
constructor
}
public void display()
{
super.display(); //calling super class method
System.out.println("Speed"+super.speed);//Accesing
super class instance variable
}
}
class Test
{
public static void main(String args[])
{
Car c=new Car("BMW",2021,700000);
c.display();
}
}
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding. (or Two or more methods having a same method signature but present two
different classes).
Advantages of Method Overriding:
Method overriding is used to provide the specific implementation of a method which is
already provided by its super class.
Method overriding is used for runtime polymorphism
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle
{
void run() //Overrided Method
{
System.out.println("Vehicle is running");
}
public static void main(String args[])
{
//creating an instance of child class
Bike obj = new Bike();
Vehicle b=new Bike();//Run time Polymorphism
//calling the method with child class instance
obj.run();
}
}
Difference between method overloading and method overriding
No. Method Overloading Method Overriding
1) Method overloading is used to increase the Method overriding is used to provide
readability of the program. the specific implementation of the
method that is already provided by
its super class.
2) Method overloading is performed within class. Method overriding occurs in two
classes that have IS-A (inheritance)
relationship.
3) In case of method overloading, parameter must be In case of method
different. overriding, parameter must be same.
4) Method overloading is the example of compile Method overriding is the example
time polymorphism. of run time polymorphism.
5) In java, method overloading can't be performed by Return type must be same or
changing return type of the method only. Return covariant in method overriding.
type can be same or different in method
overloading. But you must have to change the
parameter.
Final Keyword
The final keyword in java is used to restrict the user. The final keyword can be used in many
context.
Final can be:
1. variable
2. method
3. class
1) final variable
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}
Output: Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
class Bike
{
final void run();//final method
{
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();
}
}
Output: Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
final class Bike //final class
{
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();
}
}
Output: Compile Time Error
Object Casting
A process of converting one data type to another is known as type casting. In Java, the object can
also be typecasted like the datatypes. Parent and Child objects are two types of objects. So, there
are two types of typecasting possible for an object, i.e., Parent to Child and Child to Parent or
can say Downcasting and Upcasting.
1) Upcasting
Upcasting is a type of object typecasting in which a child object is typecasted to a parent class
object. By using the Upcasting, we can easily access the variables and methods of the parent
class to the child class. Upcasting is also known as Generalization and Widening.
class Parent{
void PrintData() {
System.out.println("method of parent class");
}
}
2) Downcasting
Downcasting is another type of object typecasting. In Downcasting, we assign a parent class
reference object to the child class. In Java, we cannot assign a parent class reference object to the
child class, but if we perform downcasting, we will not get any compile-time error.
Instance of operator
The java instanceof operator is used to test whether the object is an instance of the specified type
(class or subclass or interface).
class Simple
{
public static void main(String args[])
{
Simple s=new Simple();
System.out.println(s instanceof Simple);//true
}
}
}
abstract double bonus();
}
class Sales extends Dept
{
Sales(double bpay)
{
super(bpay);
}
public double bonus()
{
return(0.20*bpay);
}
}
class Test
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter basic pay::");
double bp=sc.nextDouble();
Sales s=new Sales(bp);
s.disp();
System.out.println("bonus for sales dept=" +s.bonus());
}
}
Interface
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
An interface is declared by using a keyword interface. It provides total abstraction; means all the
methods in an interface are abstract methods, and all the fields (variables) are public, static and
final (constants) by default. A class that implements an interface must implement all the
methods declared in the interface.
The two main reasons to use interface..
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance
Syntax:
interface <interface_name>
{
Variables declaration; //By default variables (fields) are
public static final
Methods declaration; //By default methods will public abstract
Example:
interface Area
{
double pi=3.14; //constant
double calcArea(double radius);//Abstract method
}
class Circle implements Area
{
public double calcArea(double radius)
{
return (pi*radius*radius);
}
public static void main(String args[])
{
Circle c=new Circle();
System.out.println("Area of Circle::"+c.calcArea(2));
Multiple Inheritance
If a class implements multiple interfaces it is known as multiple inheritance
interface A
{
void eat();
}
interface B
{
void sleep();
}
class Human imolements A,B
{
public void eat()
{
System.out.println("Eating.....");
}
public void sleep()
{
System.out.println("Sleeping.....");
}
public static void main(String ags[])
{
Human h=new Human();
h.eat();
h.sleep();
}
}
Differences between abstract class and interface that are given below
Abstract class Interface
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}
Packages
A package represents a directory that contains related group of classes' and interfaces.
There are several following advantages of package concept:
Packages are useful to arrange related classes and interfaces into a group. This makes all
the classes and interfaces performing the same task to put together in the same package.
For example, in Java, all the classes and interfaces which perform input and output
operations are stored in java. io package.
Packages hide the classes and interfaces in a separate sub directory, so that accidental
deletion of classes and interfaces will not take place.
The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes. For example, there is a Date class in java. util package and also there is another
"Date class available in java. sq1 package.
This reusability nature of packages makes programming easy.
java.awt: awt stands for abstract window toolkit. This package helps to develop GUI
(Graphics User Interface). It consists of an important sub package, java.awt.event, which
is useful to provide action for components like push buttons, radio buttons, menus etc.
java.applet: Applets are programs which come from a server into a client and get
executed on the client machine on a network. Applet class of this package is useful to
create and use applets.
java.io: io stands for input and output. This package contains streams. A stream
represents flow of data from one place to another place. Streams are useful to store data
in the form of file and also to perform input-output related tasks.
Accessing package
There are three ways to access the package from outside the package.
1. import package.*;
Example: import java.lang,*;
If you use package.* then all the classes and interfaces of this package will be accessible.
2. import package.classname;
Example: import java.util.Scanner;
If you import package.classname then only declared class (Scanner class) of this package
will be accessible.
3. fully qualified name
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
Example:
User-defined Packages
Just like the Built-in packages shown earlier, the users can also create their own packages. They
are called user-defined packages. User-defined packages can also be imported into other classes
and used exactly in the same way as the Built-in packages.
Let us see how to create a package of our own and use it in any other class. To create a package
the keyword package used as:
package packageName; //to create a package
package packageName.subpackageName; // to create a sub package within a package
The above statements in fact create a directory with the given package name. We can add our
classes and interfaces to this directory.
In the below program, we are creating a package with the name mypack and adding a class
Addition to it.
This Addition class: has a method void sum ( ) which performs addition of two given numbers.
package mypack;
public class Addition
{
double a,b;
public Addition(double a,double b)
{
this.a=a;
this.b=b;
}
public void sum()
{
System.out.println("Sum=="+(a+b));
}
}
Note: Dynamic Binding and Run Time polymorphism both are the
same