Chapter Three
Chapter Three
class classname {
type instance-variable1;
type instance-variable2;
... Data
type instance-variable N;
type methodname1(parameter-list) {
// body of method
}
... Methods
type methodname N(parameter-list) {
//body of method
} 4
}
Object and Class Example:
6
Initialization through reference
Initializing an object means storing data into the object.
Let us see a simple example where we are going to initialize the object through a reference
variable
▰ It is used to achieve the reusability of code. We write a method once and use it
many times. We don’t require to write code again and again.
10
Cont..
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
It is also possible that a method has the same name as another method name in the same class,
it is known as method overloading.
Predefined Method:
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods.
It is also known as the standard library method or built-in method. We can directly use these
methods just by calling them in the program at any point
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
11
Predefined Method:
public class Default_Methods {
public static void main(String[] args) {
// using math() && sqrt() method of Math class
System.out.println("The Maximum Number is: "+Math.max(20, 15));
System.out.println("The Square root is:"+Math.sqrt(25));
}
}
In the above example, we have used four predefined methods main(), print(), sqrt(), and
max().
We have used these methods directly without declaration because they are predefined
The print() method is a method of PrintStream class that prints the result on the console.
The max() and sqrt() method is a method of the Math class that returns the greater of two
numbers and the square root of a number 12
User-defined Method:
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement
Let us create a user-defined method that checks whether the number is even or odd. First, we
will define the method.
//user-defined method
public static void findEvenOdd(int num) {
//method body
If (num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
} 13
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. When we call or invoke a user defined
method, the program control transfer to the called method
public class Addition {
public static void main(String[] args){
int a = 19; int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters Output
System.out.println("The sum of a and b is= " + c);
} The sum of a and b is= 24
//user defined method
public static int add(int n1, int n2) {
int s;
s=n1+n2;
return s; //returning the sum
}
} 14
Static Method:
A method that has static keywords is known as the static method.
In other words, a method that belongs to a class rather than an instance of a class is known as
a static method.
We can also create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object.
It can access static data members and change their value of it.
It is used to create an instance method.
It is invoked by using the class name. The best example of a static method is the main()
method
15
Static Method:
public class Display { public class StaticDemo {
public static void main(String[] args){ int width;
show(); int length;
int result;
} public static void main(String[] args) {
static void show() { // TODO Auto-generated method stub
System.out.println("It is an example of static show();
method."); }
} static void show() {
} StaticDemo stat = new StaticDemo();
stat.length = 20;
stat.width = 20;
Output stat.result = stat.length * stat.width;
System.out.println("The result is :
It is an example of static method. "+stat.result);
}
}
The result is : 400
16
Instance Method:
The method of the class is known as an instance method.
It is a non-static method defined in the class.
Before calling or invoking the instance method, it is necessary to create an object of its class
public class InstanceMethod {
int s;
public static void main(String[] args) {
// TODO Auto-generated method stub
InstanceMethod obj = new InstanceMethod();
System.out.println("The sum is:"+obj.add(12, 15));
}
public int add(int a, int b) {
s = a + b;
return s; Output
}
} The sum is: 27 17
Constructors in Java
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 is called a constructor because it constructs the values at the time of object creation.
18
Constructors in Java
class Student3{
int id;
String name;
//method to display the value of id and name Output
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){ 0 null
Student3 s1=new Student3(); //creating objects 0 null
Student3 s2=new Student3();
s1.display(); //displaying values of the object
s2.display();
}
21
}
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct objects.
public class RectangleArea {
int length, width;
RectangleArea(int w, int h) {
length = w, width = h;
} Output
int Area() {
return length * width;} Area of rectangle:200
public static void main(String[] args) {
int result;
RectangleArea obj = new RectangleArea(10, 20);
result = obj.Area();
System.out.println("Area of rectangle: "+result);
}} 22
Java Constructor
Vs Java Method
23
this Keyword in Java
In Java, this keyword is a reference variable that refers to the current object.
Usage of Java this keyword:
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 parameters, this keyword
resolves the problem of ambiguity.
24
Understanding the problem without this keyword: Example:
class Student{
int rollno;
String name;
float fee;
Student(int rollno, String name, float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
public static void main(String args[]){ Output
Student s1=new Student(111,“Jemal",5000f);
s1.display();} 0 null 0.0 25
In the previous example, parameters (formal arguments) and instance variables are same. So,
we are using this keyword to distinguish local variable and instance variable.
Solution of the previous problem by using this keyword
class Student{
int rollno;
String name; Output
float fee;
Student(int rollno, String name, float fee){ 111 Jemal
this.rollno=rollno; 5000.0
this.name=name;
this.fee=fee;}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
public static void main(String args[]){
Student s1=new Student(111,“Jemal",5000f);
s1.display();
26
}
this: to invoke current class method
You may invoke the method of the current class by using the “this” keyword.
class A{
void m(){System.out.println("hello m");
} Output
void n(){ hello n
System.out.println("hello n"); hello m
this.m(); //same as m() }
}
public static void main(String args[]){
A a=new A();
a.n();
27
}}
Method Overloading:
Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type
of input parameters or both.
Overloading is related to compile-time (or static) polymorphism.
Method overloading increases the readability of the program.
Different ways to overload the method
Method Overloading: changing no. of arguments
Method Overloading: changing data type of arguments
28
Method Overloading:
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
public class Adder {
static int add(int a, int b) { Output
return a + b;} 30
static int add(int a, int b, int c) { 21
return a + b + c;}
public static void main(String[] args) {
System.out.println(Adder.add(10, 20));
System.out.println(Adder.add(5, 6, 29
Method Overloading:
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
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack; In this example, the scope of class A and its
import pack.*; method msg() is default so it cannot be accessed
class B{ from outside the package
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}}
36
protected access modifier
The protected access modifier is accessible within package and outside the package
but through inheritance only
The protected access modifier can be applied on the data member, method, and
constructor
In following example, we have created the two packages pack and mypack
The A class of pack package is public, so can be accessed from outside the package
But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance
37
protected access modifier
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");
}}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
} Output: Hello
} 38
public access modifier
The final keyword in java is used to Stop changing the Value for variables, Stops Method
Overriding, and Stops Inheritance
The Java final keyword can be used in many contexts. Final can be: variable, method, and
class
Java final variable:
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
class Bike9{
final int speedlimit=90; //final
variable
void run() Output
{ Compile Time Error
speedlimit=400;}
public static void main(String
args[]){
Bike9 obj=new Bike9();
obj.run();
} } //end of class 40
Inheritance:
Inheritance is the process of forming a new class from an existing class or base class
The base class is also known as parent class or super class
The new class that is formed is called derived class. Derived class is also known as a child
class or sub class
Inheritance helps in reducing the overall code size of the program, which is an important
concept in object-oriented programming
Implementing inheritance in Java: For creating a sub-class which is inherited
from the base class follow the below syntax
Syntax:
class Subclass-name extends Superclass-name{
//methods and fields
} 41
Inheritance:
Inheritance is the process of forming a new class from an existing class or base class
The base class is also known as parent class or super class
The new class that is formed is called derived class. Derived class is also known as a child
class or sub class
Inheritance helps in reducing the overall code size of the program, which is an important
concept in object-oriented programming
Implementing inheritance in Java: For creating a sub-class which is inherited
from the base class follow the below syntax
Syntax:
class Subclass-name extends Superclass-name{
//methods and fields
} 42
Inheritance:
Multilevel Inheritance Example
is a process of deriving a class from another derived class
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();
}} 43
Inheritance:
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance
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.eat();
c.meow();
/c.bark();//C.T.Error}}
44
Super Keyword in Java:
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable
50
Polymorphism in Java
class Bank{
int getRateOfInterest(){return 0;}
Class Vehicle{
}
class SBI extends Bank{ void run(){System.out.println("Vehicle is
int getRateOfInterest(){return 8;} running");}
} }
class ICICI extends Bank{ class Bike2 extends Vehicle{
int getRateOfInterest(){return 7;} void run(){System.out.println("Bike is running
}
class AXIS extends Bank{
safely");}
int getRateOfInterest(){return 9;} public static void main(String args[]){
} Bike2 obj = new Bike2();
class Test2{ obj.run();
public static void main(String args[]){ }
Output:
SBI s=new SBI(); Bike is running
ICICI i=new ICICI();
AXIS a=new AXIS(); safely
System.out.println("SBI Rate of Interest:
"+s.getRateOfInterest()); Output
System.out.println("ICICI Rate of Interest:
"+i.getRateOfInterest());
SBI Rate of Interest: 8
System.out.println("AXIS Rate of Interest: ICICI Rate of Interest: 7
"+a.getRateOfInterest()); AXIS Rate of Interest: 9 51
}}
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only
through the methods of their current class
To achieve encapsulation in Java :
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variable’s values.
Benefits of Encapsulation
• The fields of a class can be made read-only or write-only.
• A class can have total control over what is stored in its fields.
• Data Hiding: The user will have no idea about the inner implementation of the class.
52
Encapsulation
Following is an example that demonstrates how to achieve Encapsulation in Java:
54
Java Abstract Class and Abstract Methods
55
Example: Java Abstract Class and Method
Though abstract classes cannot be instantiated, we can create subclasses from
them. We can then access members of the abstract class using the object of the
subclass.
abstract class Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");}}
class Main extends Language {
public static void main(String[] args) {
// create an object of Main
Main obj = new Main(); Output: This is Java programming
// access method of abstract class
// using object of Main class
obj.display();
}
}
56
Implementing Abstract Methods
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(); Output:
obj.run(); running safely
}
}
In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda subclass
57
Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods
An interface can have methods and variables just like the class but the methods declared in the
interface are by default abstract
The interface in Java is a mechanism to achieve abstraction and multiple inheritances in Java.
In other words, you can say that interfaces can have abstract methods and variables, but They cannot
have a method of body
Interfaces specify what a class must do and not how.
A Java class can implement more than one interface (multiple interfaces).
We can use an interface in a class by appending the keyword “implements” after the class name
followed by the interface name.
58
Interfaces
59
Interfaces
62
Extending Interfaces
Interface Sample{
public void msg1();
}
interface Sample2 extends Sample{
public void msg2();
} Output:
class Demo implements Sample2{ Here is Message one
public void msg1(){ Here is Message Two
System.out.println("Here is Message one");}
public void msg2(){
System.out.println("Here is Message Two");}
public static void main(String[] args) {
Sample2 sam = new Demo();// Alternative option
Demo de = new Demo();
de.msg1();
de.msg2();
63
}}
Multiple inheritance by interface in Java
If an interface extends multiple interfaces, or a class implements multiple
interfaces, it is known as multiple inheritance
interface Printable{
void printMsg();
}
interface Showable{ Get to the Safe zone
void showMsg(); Message Displayed
}
class TestInterface2 implements Printable, Showable{
public void printMsg(){System.out.println("Get to the Safe zone");}
public void showMsg(){System.out.println("Message Displayed");}
public static void main(String args[]){
TestInterface2 obj = new TestInterface2();
obj.printMsg();
obj.showMsg(); } } 64
1. What is the difference between the java constructor and the
java method? 2pt
2. What is interfaces in java? 1.5 pt.
3. What are the rules in method overloading in java? 1.5pt
65
66