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

App Unit 2

APP unit 2 notes, high quality study material.

Uploaded by

lasavop349
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)
29 views

App Unit 2

APP unit 2 notes, high quality study material.

Uploaded by

lasavop349
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/ 76

Java Functions

• Java is one of the most popular programming


languages in the world, and one of its key features is
its ability to define and use functions.
• Functions in Java are blocks of code that perform a
specific task, and they are used to organize code and
make it more modular and reusable.
Defining a Java Function
In order to define a function in Java, you use the keyword
"public" (or "private" or "protected") followed by the return type
of the function, then the name of the function, and finally a set of
parentheses containing any parameters the function may take. For
example, here is a simple function that takes no parameters and
returns nothing:
public void sayHello()
{
System.out.println("Hello, world!");
}
sayHello();
FunctionExample.java
import java.util.Scanner;
public class FunctionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num1 = scanner.nextInt();
System.out.print("Enter another number: ");
int num2 = scanner.nextInt();
int sum = add(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum + ".");
public static int add(int a, int b) {
return a + b;
}
}
Output:
Enter a number: 5
Enter another number: 7
The sum of 5 and 7 is 12.
How to Call a Method in Java
• In Java, the method is a collection of statements that
performs a specific task or operation. It is widely used
because it provides reusability of code means that write
once and use it many times.
• It also provides easy modification. Each method has its
own name by which it is called. When the compiler reads
the method name, the method is called and performs the
specified task.
• In this section, we will learn how to call pre-defined,
user-defined, static, and abstract methods in Java.
Calling Static Method in Java
• In Java, a static method is a method that is
invoked or called without creating the object of the
class in which the method is defined.
• All the methods that have static keyword before
the method name are known as static methods.
We can also create a static method by using the
static keyword before the method name. We can
call a static method by using the
ClassName.methodName.
• The best example of the static method is the
main() method. It is called without creating the
object.
StaticMethodCallExample.java
import java.util.*;
public class StaticMethodCallExample
{
public static void main(String args[])
{
int a;
//calling static method of the Math class
a=Math.min(23,98);
System.out.println("Minimum number is: " + a);
}
}
Output:
Minimum number is 23
Calling User-Defined Method in Java
• To call a user-defined method, first, we create a
method and then call it. A method must be
created in the class with the name of the
method, followed by parentheses (). The method
definition consists of a method header and
method body.
• We can call a method by using the following:
• 1.method_name(); //non static method calling
• If the method is a static method, we use the
following:
• 1.obj.method_name(); //static method calling
• Where obj is the object of the class.
• In the following example, we have created two
user-defined methods named showMessage()
and displayMessage(). The showMessage()
method is a static method and displayMessage()
method is a non-static method.
• Note that we have called the showMessage()
method directly, without using the object. While
the displayMessage() method is called by using
the object of the class.
MethodCallExample.java
public class MethodCallExample
{
//user-defined static method
static void showMessage()
{
System.out.println("The static method invoked.");
}
//user-defined non-static method
void displayMessage()
{
System.out.println("Non-static method invoked.");
}
public static void main(String[] args)
{
//calling static method without using the object
showMessage(); //called method
//creating an object of the class
MethodCallExample me=new MethodCallExample();
//calling non-static method
me.displayMessage(); //called method
}
}
Output:
• The static method invoked.
• Non-static method invoked.
• When a class has two or more methods with the same
name it is differentiated by either return type or types of
parameter or number of parameters. This concept is
called method overloading. For example:
• 1.int sum(int x, int y);
• 2.double sum(double x, double y);
• The above two methods have the same name sum() but
both are different. The first sum() method returns an int
value and parses two integer x and y as parameters.
While the second sum() method returns a double value
and parses two double values a and y as parameters.
• Let's create a program that overloads sub() method.
MethodOverloadingExample.java
public class MethodOverloadingExample
{
static int sub(int x, int y)
{
return x - y;
}
static double sub(double x, double y)
{
return x - y;
}
public static void main(String[] args)
{
int a = sub(45, 23);
double b = sub(23.67,10.5);
System.out.println("subtraction of integer values: "
+a);
System.out.println("subtraction of double values: " +
b);
}}
Output:
subtraction of integer values: 22
subtraction of double values: 13.170000000000002
Object-Oriented Programming Paradigm
Abstraction
• Abstract class in Java
• A class which is declared with the abstract keyword is
known as an abstract class in Java. It can have abstract
and non-abstract methods (method with the body).
• Abstraction in Java
• 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.
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.
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.
• It can have final methods which will force the subclass
not to change the body of the method.
Example of abstract class
abstract class A{}
Abstract Method in Java
A method which is declared as abstract and
does not have implementation is known as
an abstract method.
Example of abstract method
abstract void printStatus();//no method body
and abstract
Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only
one abstract method run. Its implementation is provided by
the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}}
Output:
running safely
Encapsulation in Java
• Encapsulation in Java is a process of wrapping code and
data together into a single unit.
• Advantage of Encapsulation in Java
• By providing only a setter or getter method, you can
make the class read-only or write-only.
• It provides you the control over the data.
• It is a way to achieve data hiding in Java because other
class will not be able to access the data through the
private data members.
• The encapsulate class is easy to test. So, it is better for
unit testing.
• The standard IDE's are providing the facility to generate
the getters and setters. So, it is easy and fast to create
an encapsulated class in Java.
Test.java
//A Java class to test the encapsulated class.
package com.javatpoint;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output:
vijay
Read-Only class
//A Java class which has only getter methods.
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}}
Now, you can't change the value of the college data member which is
"AKG".
s.setCollege("KITE");//will render compile time error
Write-Only class
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
this.college=college;
}
}
Inheritance in Java
• 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.
• Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.
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.
• Java Inheritance Example

• Programmer is the subclass and Employee is the


superclass. The relationship between the two
classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can
access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
There can be three types of inheritance in
java: single, multilevel and hierarchical.In java
programming, multiple and hybrid inheritance is
supported through interface only.
• Note: Multiple inheritance is not supported in
Java through class.
• When one class inherits multiple classes, it is
known as multiple inheritance. For Example:
Single Inheritance Example
• When a class inherits another class, it is known as a
single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single
inheritance.
File: TestInheritance.java
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");
} }
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as
multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel
inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Hierarchical Inheritance
Example
When two or more classes inherits a single class, it is
known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so
there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Why multiple inheritance is not supported in java?

• To reduce the complexity and simplify the language,


multiple inheritance is not supported in java.
• Consider a scenario where A, B, and C are three classes.
The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B
class.
• Since compile-time errors are better than runtime errors,
Java renders compile-time error if you inherit 2 classes.
So whether you have same method or different, there will
be compile time error.
Polymorphism
Method Overloading in Java
• If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.
• If we have to perform only one operation, having same
name of the methods increases the readability of the
program.
• Suppose you have to perform addition of the given
numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to
understand the behavior of the method because its
name differs.
Advantage of method overloading
• Method overloading increases the readability of the
program.
• Different ways to overload the method
There are two ways to overload the method in java
1.By changing number of arguments
2.By changing the data type
Method Overloading
In Java, Method Overloading is not possible by changing
the return type of the method only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add()
method performs addition of two numbers and second add
method performs addition of three numbers.
In this example, we are creating static methods so that we
don't need to create instance for calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs
in data type. The first add method receives two integer
arguments and second add method receives two double
arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Why Method Overloading is not possible by changing the
return type of method only?

In java, method overloading is not possible by changing the


return type of the method only because of ambiguity. Let's
see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined
in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java
determine which sum() method should be called?
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.
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).
A real example of Java Method
Overriding
• Consider a scenario where Bank is a class that provides
functionality to get the rate of interest. However, the rate of
interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of
interest.
Interface in Java
• An interface in Java is a blueprint of a class. It has static
constants and abstract methods.
• The interface in Java is a mechanism to achieve
abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method
body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in
an interface.
• Since Java 9, we can have private methods in an
interface.
Why use Java interface?
There are mainly three reasons to use interface. They are
given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple
inheritance.
• It can be used to achieve loose coupling.
How to declare an interface?
• An interface is declared by using the interface keyword.
It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the
fields are public, static and final by default. A class that
implements an interface must implement all the methods
declared in the interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
interface

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.
Java Interface Example: Drawable
In this example, the Drawable interface has only one
method. Its implementation is provided by Rectangle and
Circle classes.
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
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();
}}
Output:
drawing circle
Multiple inheritance in Java by interface

• If a class implements multiple interfaces, or an


interface extends multiple interfaces, it is known
as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
Nested Interface in Java
Note: An interface can have another interface which is
known as a nested interface. We will learn it in detail in the
nested classes chapter. For example:

interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Java Package
• A java package is a group of similar types of classes,
interfaces and sub-packages.
• Package in java can be categorized in two form, built-in
package and user-defined package.
• There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and
using user-defined packages.
• Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax
given below:
1.javac -d directory javafilename
For example
1.javac -d . Simple.java
The -d switch specifies the destination where to
put the generated class file. You can use any
directory name like /home (in case of Linux),
d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you
can use . (dot).
How to run java package program
You need to use fully qualified name e.g.
mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to
put the class file i.e. it represents destination. The .
represents the current folder.
How to access package from another package?

There are three ways to access the package from


outside the package.
1.import package.*;
2.import package.classname;
3.Fully Qualified Name.
1) Using packagename.*

• If you use package.* then all the classes and


interfaces of this package will be accessible but
not subpackages.
• The import keyword is used to make the classes
and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello
2) Using packagename.classname
• If you import package.classname then only
declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello
3) Using 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.
• It is generally used when two packages have
same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import
fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualif
ied name
obj.msg();
}
}
Output: Hello
Subpackage in java
Package inside the package is called the subpackage. It should be
created to categorize the package further.
Example of Subpackage

package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
How to put two public classes in a package?
If you want to put two public classes in a package,
have two java source files containing one public
class, but keep the package name same. For
example:
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}

You might also like