0% found this document useful (0 votes)
9 views

Chapter2_Notes java

Uploaded by

sakibmujawar108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chapter2_Notes java

Uploaded by

sakibmujawar108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER - 2

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;
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 1


CHAPTER - 2

public static void change() //Static Method


{
college="KLEBCA";
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}

public class Test


{
public static void main(String args[])
{
Student s1 = new Student(111,"ABC");
Student s2 = new Student(222,"XYZ");
Student.change();// Calling Static method
s1.display();
s2.display();
}
}

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 {

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 2


CHAPTER - 2

.....
.....
}
 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

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 3


CHAPTER - 2

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);

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 4


CHAPTER - 2

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)

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 5


CHAPTER - 2

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
{

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 6


CHAPTER - 2

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 class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class provides some common behaviour to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 7


CHAPTER - 2

Methods of Object class


Method Description
public final Class getClass() Returns the Class class object of this object. The
Class class can further be used to get the metadata of
this class.
public int hashCode() Returns the hashcode number for this object.
public boolean equals(Object obj) Compares the given object to this object.
protected Object clone() throws Creates and returns the exact copy (clone) of this
CloneNotSupportedException object.
public String toString() Returns the string representation of this object.
public final void notify() Wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() Wakes up all the threads, waiting on this object's
monitor.
public final void wait(long Causes the current thread to wait for the specified
timeout)throws InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long timeout,int Causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws Causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
protected void finalize()throws is invoked by the garbage collector before object is
Throwable being garbage collected.

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.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 8


CHAPTER - 2

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");
}
}

class Child extends Parent {


void PrintData() {
System.out.println("method of child class");
}
}
class UpcastingExample{
public static void main(String args[])
{

Parent obj1 = (Parent) new Child();


Parent obj2 = (Parent) new Child();
obj1.PrintData();
obj2.PrintData();
}
}

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
}
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 9


CHAPTER - 2

Abstract class and Method


Abstraction is a process of hiding the implementation details and showing only functionality to
the user. Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
There are two ways to achieve abstraction in java
1. Partial Abstraction is achieved with the help of Abstract class (0 to 100%)
2. Full Abstraction is achieved with the help of Interface (100%)
Abstract class
 When a class contains one or more abstract methods then it should be declared as
abstract.
 A class which is declared as abstract is known as an abstract class.
 It can have abstract methods (Method without a body) and non-abstract methods
(concrete method or method with a body).
 An abstract method is a method that is declared with only its signature, it has no
implementation. That means method without body.
 Abstract class is used to provide common properties.
 It needs to be extended and its abstract method needs to be implemented.
 It cannot be instantiated or not possible to create the object
Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
Example:
abstract class Dept
{
double bpay;
Dept(double bpay)
{
this.bpay=bpay;
}
void disp()
{
System.out.println("Basic pay="+bpay);

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 10


CHAPTER - 2

}
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

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 11


CHAPTER - 2

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));

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Multiple Inheritance
 If a class implements multiple interfaces it is known as multiple inheritance

interface A
{
void eat();
}
interface B
{
void sleep();

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 12


CHAPTER - 2

}
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();
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 13


CHAPTER - 2

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.

Different Types of Packages


There are two different types of packages in Java. They are:
1. Built-in packages
2. User-defined packages
Built-in Packages
These are the packages which are already available in Java language. These packages provide all
most all necessary classes, interfaces and methods for the programmer to perform any task in his
programs.
Some of the important built in packages of Java
java.lang: lang stands for language. This package got primary classes and interfaces
essential for developing a basic Java program. It consists of wrapper classes which are
useful to convert primitive data types into objects. There are classes like String,
StringBuffer to handle strings. There is a Thread class to create various individual
processes.
java.util: util stands for utility. This package contains useful classes and interfaces like
Stack, LinkedList, Hashtable, Vector, Arrays, etc. These classes are called collections.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 14


CHAPTER - 2

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

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 15


CHAPTER - 2

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));
}
}

Compiling the package:


 javac - d. Addition.java
The option (-d) tells the- Java compiler to create a separate sub directory and place the .class file
in there. The dot (.) after -d indicates that the package should be created in the current directory.
Using a package
Accessing package with import statement
import mypack.Addition;
class Demo
{
public static void main(String args[])
{
Addition a=new Addition(10,20);
a.sum();
}
}

Accessing package with fully qualified name


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

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 16


CHAPTER - 2

mypack.Addition a=new mypack.Addition(10,20);


a.sum();
}
}

Note: Dynamic Binding and Run Time polymorphism both are the
same

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 17

You might also like