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

Chapter Three

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

Chapter Three

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

Chapter-Three

Classes, Objects, and Methods

Compiled By: Minichil A.


Introduction to Classes and Object

What is an object in Java?


 An entity that has a state and behavior is known as an object e.g.,
table, car, etc.
 It can be physical or logical (tangible and intangible).
 An object has three characteristics:
o An object is an instance of a class.
o An object is a real-world entity.
o An object is a runtime entity. 2
What is a class in Java?

 A class is a group of objects which have common properties.


 It is a template or blueprint from which objects are created.
 It is a logical entity. It cannot be physical.
 A class in Java can contain: Fields, Methods, Constructors, Blocks, Nested class,
and interface
 Method in Java: In Java, a method is like a function which is used to expose the
behavior of an object.
 “new” keyword in Java: It is used to allocate memory at runtime. All objects get
memory in the Heap memory area 3
The General Form of a Class

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:

public class Student {


//declaring instance variables
int id;
String name;
public static void main(String[] args) Output
{
//Creating an object or instance
0
Student stud = new Student(); null
//Creating an object
System.out.println(stud.id);
System.out.println(stud.name);
}
}
5
Initialize object in Java:

▰ There are 3 ways to initialize object in Java.


▰ 1. By reference variable
▰ 2. By method
▰ 3. By constructor

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

public class Student {


//declaring instance variables
int id;
String name; Output
public static void main(String[] args) {
Student stud = new Student(); //Creating an object 100 Kebede
//object instantiating through reference
stud.id = 100;
stud.name = "Kebede";
System.out.println(stud.id + " " + stud.name);
}
7
}
Initialization through method
public class Student {
int rollno;
String name;
void insertRecord(int r, String n) {
rollno = r;
name = n;
}
void displayInformation() {
System.out.println(rollno + " "+name);} Output
class Student2{ 120 Abriham
public static void main(String[] args) { 240 Chaltu
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(120, "Abriham");
s2.insertRecord(240, "Chaltu");
s1.displayInformation();
s2.displayInformation();}}} 8
Methods in Java

▰ A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation.

▰ 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.

▰ The method is executed only when we call or invoke it.

▰ The most important method in Java is the main() method.


9
Method Declaration:

 The method declaration provides information about method attributes, such as


visibility, return type, name, parameters, and arguments.
 It has six components that are known as method header, as we have shown in the
following figure.

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

 Rules for creating Java constructor:


 There are three 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

 Types of Java constructors: There are two types of constructors in Java:


 Default constructor (no-arg constructor)
 Java Parameterized Constructor 19
Default constructor (no-arg constructor)

 A constructor is called "Default Constructor" or “no-arg Constructor” when it


does not have any parameter.
 Syntax: <class_name>(){}
public class DefaultConstructor {
DefaultConstructor() {
System.out.println("Here is default constructor");
}
public static void main(String[] args) {
DefaultConstructor defcon = new DefaultConstructor();
} Output
}
Here is default constructor
20
Default constructor (no-arg constructor)

 Rule: If there is no constructor in a class, compiler automatically creates a default


constructor. Here 0 and null values are provided by default constructor.

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

A constructor is used to initialize the A method is used to expose the behavior of


state of an object an object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly The method is invoked explicitly
The constructor name must be same as The method name may or may not be same
the class name. as the class name

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

public class Adder2 {


static int add(int a, int b) {
return a + b;} Output
static double add(double a, double b) { 20
return a + b;} 11.8
public static void main(String[] args) {
System.out.println(Adder.add(10, 10));
System.out.println(Adder.add(5.3,
30
6.5));}}
Constructor Overloading:
 In Java, we can overload constructors like methods.
 The constructor overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can perform a different task.
public class Test {
int id;
String fname;
Test(){
System.out.println("This is default constructor");
System.out.println("Default constructor values: "+id+"
"+fname);}
Test(int a, String name){
id = a;
fname = name; Output
System.out.println("Here is Overload Constructor"); This is default constructor
System.out.println("Overload Constructor values: "+a+" Default constructor values: 0 null
"+name);} Here is Overload Constructor
public static void main(String[] args) { Overload Constructor values: 12
Test te = new Test(); Derartu
//new Test();
Test tee = new Test(12, "Derartu");}}
31
Recursion in Java
 Recursion in java is a process in which a method calls itself continuously
 A method in java that calls itself is called recursive method
public class Factorial {
static int factorial(int n) { Output
if (n==1) Factorial of 5 : 120
return 1; Factorial of 4 : 24
else
return (n * factorial(n-1));}
public static void main(String[] args) {
System.out.println("Factorial of 5 :
"+Factorial.factorial(5));
System.out.println("Factorial of 4 : "+factorial(4));}}
32
Access Control
 Access Modifiers in java:
 There are two types of modifiers in java: access modifiers and non-access
modifiers.
 The access modifiers in java specifies accessibility (scope) of a data member,
method, constructor, or class
 There are 4 types of java access modifiers:
1. private access modifier:
2. default access modifier
3. protected access modifier
33
4. public access modifier
Access Control
 private access modifier:
 The private (most restrictive) modifiers can be used for members but
cannot be used for classes and Interfaces
 Fields, methods or constructors declared private are strictly controlled,
which means they cannot be accessed by anywhere outside the enclosing
class Test3 {
class. private int data = 40;
private void msg() {
System.out.println("Hello Java");}}
class AccessTest{
public static void main(String args[]) {
Test3 obj = new Test3();
System.out.println(obj.data); //Leads compile
time error
obj.msg(); // leads to compile time error
} 34
}
default access modifier

 The default access level is declared by not writing any access


modifier at all
 Any class, field, method or constructor that has no declared access
modifier is accessible only by classes in the same package.
 In the following example, we have created two packages pack and mypack.
 We are accessing the A class from outside its package, since A class is not public, so
it cannot be accessed from outside the package
35
default access modifier

//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 public access modifier is accessible everywhere.


 It has the widest scope among all other modifiers
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*; Output: Hello
class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); } }
39
final Keyword

 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

Usage of Java super Keyword:


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor
45
Super Keyword in Java:

1) super is used to refer immediate parent class instance variable.


 It is used if parent class and child class have same data members. In that case there is a
possibility of ambiguity for the JVM
class Animal{
String color="white";
}
class Dog extends Animal{ Output
String color="black"; black
void printColor(){
white
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class }
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}} 46
Super Keyword in Java:
2) super can be used to invoke parent class method.
 The super keyword can also be used to invoke parent class method.
 It should be used if subclass contains the same method as parent class.
 In other words, it is used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
} Output
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
eating…
void bark(){System.out.println("barking...");} barking
void work() {
super.eat();
bark(); }}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
47
}}
Polymorphism in Java

 Polymorphism in Java is a concept by which we can perform a single


action in different ways
 There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
 We can perform polymorphism in java by method overloading and
method overriding
 If you overload a static method in Java, it is the example of compile time
polymorphism. 48
Polymorphism in Java
 Method Overriding:
 Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes
 If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
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.
49
3. There must be an IS-A relationship (inheritance).
Polymorphism in Java
Example of 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.

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:

public class EncapTest { class Runcap


private String name; {
private String idNum; public static void main(String[] args)
private int age; {
public int getAge() { EncapTest encap = new EncapTest();
return age; } encap.setName("James");
public String getName() { encap.setIdNum("Cir/026");
return name; } encap.setAge(35);
public String getIdNum() { System.out.println("Name : " + encap.getName() +
return idNum;} " Age : " + encap.getAge() + " "+"ID : "+encap.getIdNum());
public void setAge(int newAge) {
age = newAge; } }
public void setName(String newName) { }
name = newName;}
Output: Name : James Age : 35 ID : Cir/026
public void setIdNum(String newId) {
idNum = newId;
}} 53
Abstract class
 A class that is declared as abstract is known as an abstract class.
 An Abstract class is a class that contains abstract as well as concrete methods or class
 An Abstract class can't be instantiated in other words. We cannot create the object of an abstract class
 An abstract class is a class that has at least one abstract method, and maybe there can be some regular
methods.
 An abstract class can have static methods and constructors.
 To use an abstract class, you have to inherit it from another class and provide implementations to the
abstract methods in it

54
Java Abstract Class and Abstract Methods

Java Abstract Class abstract class Language {


//create an abstract class
abstract class Language { // abstract method
// fields and methods abstract void method1();
}
... // regular method
//try to create an object Language void method2() {
//throws an error System.out.println("This is regular method");
Language obj = new Language(); }
}
 The abstract class in Java cannot be  An abstract class can have both regular methods
instantiated (we cannot create objects of and abstract methods.
abstract classes).

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

 An interface is similar to a class in the following ways −


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

59
Interfaces

 However, an interface is different from a class in several ways, including −


 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
60
Implementing Interfaces
 When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface.
public interface Interface_one {
public void method1();
public void method2();}
class Demo implements Interface_one{
public void method1(){ Output
System.out.println("Here is Method 1");} Here is Method 1
public void method2() { Here is Method 2
System.out.println("Here is Method 2"); }
public static void main(String[] args) {
Demo de = new Demo();
de.method1();
de.method2(); }}
61
Implementing Interfaces
 When implementation interfaces, there are several rules
 A class can implement more than one interface at a time.
 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another
class.
 Extending Interfaces
 An interface can extend another interface in the same way that a class can extend another
class.
 The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface

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

You might also like