0% found this document useful (0 votes)
8 views40 pages

Java Object-Oriented Programming Concepts

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Java, including inheritance, encapsulation, polymorphism, and abstraction. It explains methods, static variables, method overloading, recursion, and the four pillars of OOP, along with additional terms like coupling and cohesion. Furthermore, it covers Java naming conventions, access modifiers, constructors, and practical examples of creating classes and methods.

Uploaded by

pranavireddy289
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)
8 views40 pages

Java Object-Oriented Programming Concepts

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Java, including inheritance, encapsulation, polymorphism, and abstraction. It explains methods, static variables, method overloading, recursion, and the four pillars of OOP, along with additional terms like coupling and cohesion. Furthermore, it covers Java naming conventions, access modifiers, constructors, and practical examples of creating classes and methods.

Uploaded by

pranavireddy289
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

OBJECT
ORIENTED OOPs
Concepts
PROGRAMMING
Object Oriented Programming:-
Inheritance , Encapsulation ,
Polymorphism ,Abstraction

Uday Sharma
mrudaysharma4600@[Link]
1 OOPS in JAVA
• Methods in Java:-
• Sometimes our program grows in size, and we want to separate the logic of the main
method from the other methods.
• For instance, if we calculate the average of a number pair 5 times, we can use methods
to avoid repeating the logic. [DRY – Don’t Repeat Yourself].
• Syntax of a Method:-
A method is a function written inside a class. Since Java is an object-oriented language, we need
to write the method inside some class.
• Syntax of a method :
returnType nameOfMethod() {
//Method body
}

• Java Static keyword : -


1. Java static Methods:-
• The static keyword is used to associate a method of a given class with the class rather
than the object.
• You can call a static method without creating an instance of the class.
• In Java, the main() method is static, so that JVM can call the main() method directly
without allocating any extra memory for object creation.
• All the objects share the static method in a class.
• 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.
2

• Calling a Method by creating a class object : -


A method can be called by creating an object of the class in which the method exists followed by
the method call:

Output is same in both the case:-

• Void return type : -


When we don’t want our method to return anything, we use void as the return type.
3 • Method Overloading in Java:-
• In Java, it is possible for a class to contain two or more methods with the same name
but with different parameters. Such methods are called Overloaded methods.
• Method overloading is used to increase the readability of the program.
• Ways to perform method overloading : -
In Java, method overloading can be performed by two ways listed below :
1. By changing the return type of the different methods
2. By changing the number of arguments accepted by the method
Now, let's have an example to understand the above ways of method overloading :
1. By changing the return type of the different methods:-

2). By changing the number of arguments accepted by the method:-


4

Output:-

2). Java 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 in the class area at the time of class loading.
5
• Advantages of static variable:-
It makes your program memory efficient (i.e., it saves memory).
• Arguments (VarArgs) in Java:-
• you want to overload an "add" method. The "add" method will accept one argument for the first time
and every time the number of arguments passed will be incremented by 1 till the number of
arguments is equaled to 10.
• One approach to solve this problem is to overload the "add" method 10 times. But is it the optimal
approach? What if I say that the number of arguments passed will be incremented by 1 till the
number of arguments is equaled to 1000. Do you think that it is good practice to overload a method
1000 times?
• To solve this problem of method overloading, Variable Arguments(Varargs) were introduced with the
release of JDK 5.
• With the help of Varargs, we do not need to overload the methods.
• foo can be called with zero or more arguments like this:
• sum(7)
• sum(7,8,9) // its gives the sum =7+8+9
• sum(1,2,7,8,9)
code of vargs and sum of user given array:-
6

• Recursion in Java:-
One does not simply understand RECURSION without understanding RECURSION.
• In programming, recursion is a technique through which a function calls itself.
• With the help of recursion, we can break down complex problems into simple problems.

• Fibonacci series:-
7

OBJECT ORIENTED PROGRAMMING SYSTEMS


JAVA
• Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects. It simplifies the software development and maintenance by providing
some concepts defined below :
• Class is a user-defined data type which defines its properties and its functions. Class is
the only logical representation of the data. For example, Human being is a class. The body
parts of a human being are its properties, and the actions performed by the body parts are
known as functions. The class does not occupy any memory space till the time an object is
instantiated.
• Object is a run-time entity. It is an instance of the class. An object can represent a person,
place or any other item. An object can operate on both data members and member
functions.
Four pillars of Object-Oriented-Programming Language :-
1. Abstraction :-
• Let's suppose you want to turn on the bulb in your room. What do you do to switch on the
bulb. You simply press the button and the light bulb turns on. Right? Notice that here you're
only concerned with your final result, i.e., turning on the light bulb. You do not care about the
circuit of the bulb or how current flows through the bulb. The point here is that you press
the switch, the bulb turns on! You don't know how the bulb turned on/how the circuit is
made because all these details are hidden from you. This phenomenon is known as
abstraction.
• More formally, data abstraction is the way through which only the essential info is shown to
the user, and all the internal details remain hidden from the user.
2. Polymorphism :
• One entity many forms.
• The word polymorphism comprises two words, poly which means many, and
morph, which means forms.
• In OOPs, polymorphism is the property that helps to perform a single task in
different ways.
• Let us consider a real-life example of polymorphism. A woman at the same time
can be a mother, wife, sister, daughter, etc. Here, a woman is an entity having
different forms.
• Let's take another example, a smartphone can work like a camera as well as like a
calculator. So, you can see the a smartphone is an entity having different forms.
Also :
3. Encapsulation :
• The act of putting various components together (in a capsule).
• In java, the variables and methods are the components that are wrapped inside a
single unit named class.
• All the methods and variables of a class remain hidden from any other class.
8
• A automatic cold drink vending machine is an example of encapsulation.
• Cold drinks inside the machine are data that is wrapped inside a single unit cold
drink vending machine.
4. Inheritance :
• The act of deriving new things from existing things.
• In Java, one class can acquire all the properties and behaviours of other some
other class
• The class which inherits some other class is known as child class or sub class.
• The class which is inherited is known as parent class or super class.
• Inheritance helps us to write more efficient code because it increases the
reusablity of the code.
• Example :
• Rickshaw → E-Rickshaw
• Phone → Smart Phone
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
• Coupling
• Cohesion
• Association
• Aggregation
• Composition
• Coupling:-
Coupling refers to the knowledge or information or dependency of another class. It arises when
classes are aware of each other. If a class has the details information of another class, there is strong
coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a
class, method, and field. You can use interfaces for the weaker coupling because there is no concrete
implementation.
• Cohesion:-
Cohesion refers to the level of a component which performs a single well-defined task. A single well-
defined task is done by a highly cohesive method. The weakly cohesive method will split the task
into separate parts. The [Link] package is a highly cohesive package because it has I/O related
classes and interface. However, the [Link] package is a weakly cohesive package because it has
unrelated classes and interfaces.
• Association:-
Association represents the relationship between the objects. Here, one object can be associated
with one object or many objects. There can be four types of association between the objects.
• One to One
• One to Many
• Many to One, and
• Many to Many
9 Let's understand the relationship with real-time examples. For example, One country can have one
prime minister (one to one), and a prime minister can have many ministers (one to many). Also,
many MP's can have one prime minister (many to one), and many ministers can have many
departments (many to many).
Association can be undirectional or bidirectional.
• Aggregation:-
Aggregation is a way to achieve Association. Aggregation represents the relationship where one
object contains other objects as a part of its state. It represents the weak relationship between
objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a
relationship. It is another way to reuse objects.
• Composition:-
The composition is also a way to achieve Association. The composition represents the relationship
where one object contains other objects as a part of its state. There is a strong relationship between
the containing object and the dependent object. It is the state where containing objects do not have
an independent existence. If you delete the parent object, all the child objects will be deleted
automatically.
• Java Naming Convention:-
• Java naming convention is a rule to follow as you decide what to name your identifiers such
as class, package, variable, constant, method, etc.
• But, it is not forced to follow. So, it is known as convention not rule. These conventions are
suggested by several Java communities such as Sun Microsystems and Netscape.
• All the classes, interfaces, packages, methods and fields of Java programming language are
given according to the Java naming convention. If you fail to follow these conventions, it may
generate confusion or erroneous code.
• Advantage of Naming Conventions in Java:-
• By using standard Java naming conventions, you make your code easier to read for yourself
and other programmers. Readability of Java program is very important. It indicates that less
time is spent to figure out what the code does.
Naming Conventions of the Different Identifiers:-
The following examples shows the popular conventions used for the different identifiers.
Clas,Interface ,Constant ,Variable ,Method ,Package and many more which follows CamelCase in
Java Name Convention,
Java Tutorial: Creating Our Own Java Class:-
Writing a Custom Class :
Syntax of a custom class :

class <class_name>{
field;
method;
}

Note: The first letter of a class should always be capital.


• Any real-world object = Properties + Behavior
• Object in OOPs = Attributes + Methods
There are many ways to create an object in java. They are:-
10
• By new keyword:-
Employee uday = new Employee();
• By newInstance() method:-
new Employee().info(125,210210210);
• By clone() method:-
Employee anshul=new Employee(),yadav=new Employee();
• By deserialization
• By factory method etc.
Example as code:-

Output:-

Question on java class:-


1. Create a class cellphone with methods to print “ringing…”, “vibrating…”, etc.
11 2. Create a class Square with a method to initialize its side, calculating area, perimeter etc.
3. Create a class Rectangle & problem 3.
4. Create a class TommyVecetti for Rockstar Games capable of hitting (print hitting…), running,
firing, etc.
5. Repeat problem 4 for a circle.
Code :-
• Java Tutorial: Access modifiers, getters & setters in Java
Access Modifiers
Access Modifiers specify where a property/method is accessible. There are four types of access
modifiers in java :
1. private
2. default
3. protected
4. public
outside package by subclass outside
Access Modifier within class within package
only package
public Y Y Y Y
protected Y Y Y N
Default Y Y N N
private Y N N N
Getters and Setters :
• Getter ➼ Returns the value [accessors]
• setter ➼ Sets / updates the value [mutators]
In the below code, we've created total 4 methods:
1. setName( ): The argument passed to this method is assigned to the private variable name.
2. getName( ): The method returns the value set by the setName() method.
3. setId( ): The integer argument passed to this method is assigned to the private variable id.
4. getId( ): This method returns the value set by the setId() method.
Code:-
12

Output:-

Constructors in Java:-
• Constructors in Java : -
• Constructors are similar to methods,, but they are used to initialize an object.
• Constructors do not have any return type(not even void).
• Every time we create an object by using the new() keyword, a constructor is called.
• If we do not create a constructor by ourself, then the default constructor(created by Java
compiler) is called.
• Rules for creating a Constructor :-
1. The class name and constructor name should be the same.
2. It must have no explicit return type.
3. It can not be abstract, static, final, and synchronized.
• Types of Constructors in Java :-
There are two types of constructors in Java :
1. Defaut / Non-Parameterized constructor : A constructor with 0 parameters is
known as default constructor. A constructor which has no argument is known as non-
parameterized constructor(or no-argument constructor). It is invoked at the time of
creating an object. If we don’t create one then it is created by default by Java.
Syntax :

<class_name>(){
//code to be executed on the execution of the constructor
}

2. Paramerterized constructor : A constructor with some specified number of parameters is


known as a parameterized [Link] which has parameters is called a
parameterized constructor. It is used to provide different values to distinct objects.
Syntax :
13 <class-name>(<data-type> param1, <data-type> param2,......){

//code to be executed on the invocation of the constructor


}

3. Constructor Overloading in Java :constructor used to declare and initialize an object


from another object. There is only a user defined copy constructor in Java(C++ has a default one
too).
4. CopyConstructor:- is used to copy the data of the other constructor.
public Employee (String n)
name = n;
}

Note:-
1. Constructors can take parameters without being overloaded
2. There can be more than two overloaded constructors.
3. Note : - When an object is created using a new keyword, then space is allocated for the
variable in a heap, and the starting address is stored in the stack memory.
4. ‘this’ keyword : ‘this’ keyword in Java that refers to the current instance of the class. In
OOPS it is used to:-
5. pass the current object as a parameter to another method
6. refer to the current class instance variable.
Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior of 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 Java compiler provides a default constructor if you The method is not provided by the compiler in any case.
don't have any constructor in a class.

The constructor name must be same as the class name. The method name may or may not be same as the class name.
14

• Inheritance:-
• Inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such a way, you can reuse, extend or modify the attributes
and behaviors which are defined in other classes.
• In Java, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
• Inheritance is used to borrow properties & methods from an existing class.
• Inheritance helps us create classes based on existing classes, which increases the code's
15
reusability.
• Inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such a way, you can reuse, extend or modify the attributes
and behaviors which are defined in other classes.
• In Java, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
Examples :

Important terminologies used in Inheritance :


1. Parent class/superclass: The class from which a class inherits methods and attributes is
known as parent class.
2. Child class/sub-class: The class that inherits some other class's methods and attributes
is known as child class.

Extends keyword in inheritance :


• The extends keyword is used to inherit a subclass from a superclass.
Syntax :

class Subclass-name extends Superclass-name


{
//methods and fields
}

Code:-
16

• Types of Inheritance :
1. Single inheritance : -When one class inherits another class, it is known as single level
inheritance
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
}}
2. Hierarchical inheritance:- Hierarchical inheritance is defined as the process of deriving
more than one class from a base class.
class Shape {
public void area() {
17
[Link]("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
} }
class Circle extends Shape {
public void area(int r) {
[Link]((3.14)*r*r);
} }
3. Multilevel inheritance :- Multilevel inheritance is a process of deriving a class from another
derived class.
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
} }
class EquilateralTriangle extends Triangle {
int side;
}
4. Hybrid inheritance : -Hybrid inheritance is a combination of simple, multiple inheritance and
hierarchical inheritance.
• Constructor order in the inheritance :-
When a drived class is extended from the base class, the constructor of the base class is
executed first followed by the constructor of the derived class. For the following Inheritance
hierarchy , the constructors are executed in the order:
1. C1- Parent
2. C2 - Child
3. C3 - Grandchild
• Constructors during constructor overloading :-
• When there are multiple constructors in the parent class, the constructor without any
parameters is called from the child class.
• If we want to call the constructor with parameters from the parent class, we can use the
super keyword.
• super(a, b) calls the constructor from the parent class which takes 2 variables.
Code:-
18

Output:-

• this and super keyword in Java:-


• this keyword in Java :
• this is a way for us to reference an object of the class which is being created/referenced.
• It is used to call the default constructor of the same class.
• this keyword eliminates the confusion between the parameters and the class attributes
with the same name.
19 • Super keyword :-
• A reference variable used to refer immediate parent class object.
• It can be used to refer immediate parent class instance variable.
• It can be used to invoke the parent class method.
• Final Keyword In Java:-
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only.

• Aggregation in Java:-
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.
Consider a situation, Employee object contains many informations such as id, name, email_Id etc.
It contains one more object named address, which contains its own informations such as city,
state, country, zipcode etc. as given below.
Why use Aggregation?
o For Code Reusability.
Simple Example of Aggregation
Output:-
20

• Polymorphism:-
Polymorphism is the ability to present the same interface for differing underlying forms (data
types). With polymorphism, each of these classes will have different underlying data. Precisely,
Poly means ‘many’ and morphism means ‘forms’.
• Types of Polymorphism:-
1. Compile Time Polymorphism (Static).
2. Runtime Polymorphism (Dynamic) .
• Compile Time Polymorphism : The polymorphism which is implemented at the
compile time is known as compile-time polymorphism. Example - Method Overloading .
• Method Overloading : Method overloading is a technique which allows you to have more
than one function with the same function name but with different functionality. Method
overloading can be possible on the following basis:
1. The type of the parameters/argument passed to the function.
2. The number of parameters passed to the function.
3. We can check the overloding of method in the beginning of the notes of OOPS in JAVA
programming .
• Runtime Polymorphism : Runtime polymorphism is also known as dynamic
polymorphism. Function overriding is an example of runtime polymorphism. Function
overriding means when the child class contains the method which is already present in the
parent class. Hence, the child class overrides the method of the parent class. In case of
function overriding, parent and child classes both contain the same function with a different
definition. The call to the function is determined at runtime is known as runtime
polymorphism.
• Method Overriding in Java:-
1. If the child class implements the same method present in the parent class again, it is know as
method overriding.
2. Method overriding helps us to classify a behavior that is specific to the child class.
3. The subclass can override the method of the parent class only when the method is not declared
as final.
Example :
In the below code, we've created two classes: class A & class B.
Class B is inheriting class A.
4. In the main() method, we've created one object for both classes. We're running the meth1()
method on class A and B objects separately, but the output is the same because the meth1() is
defined in the parent class, i.e., class A.
5. Overriding method is denoted by @override which denotes this method is override ,if we
override the method then we use override to detect the error . @overriding is not necessary but
it is recommended to use in the code .
Code:-
21

Output:-

• Static Binding and Dynamic Binding


static binding and dynamic binding in java
Connecting a method call to the method body is known as binding.
There are two types of binding:-
• Static Binding (also known as Early Binding).
• Dynamic Binding (also known as Late Binding).
1. static binding:-
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
22
2. Dynamic Binding Method Dispatch in Java:-
Dynamic method dispatch is also known as run time polymorphism.
1.
It is the process through which a call to an overridden method is resolved at runtime.
2.
This technique is used to resolve a call to an overridden method at runtime rather than
3.
compile time.
4. To properly understand Dynamic method dispatch in Java, it is important to understand
the concept of upcasting because dynamic method dispatch is based on upcasting.
Upcasting :
• It is a technique in which a superclass reference variable refers to the object of the
subclass.
Example :

class Animal{}
class Dog extends Animal{}
Animal a=new Dog();//upcasting

Example to demonstrate the use of Dynamic method dispatch :


• In the below code, we've created two classes: Base & Derived.
• The Base is the parent class and the Derived is the child class.
• The method on() of the parent class is overridden inside the child class.
• Inside the main() method, we've created an object obj of the Derived () class
by taking the reference of the Base() class.
• When [Link]() will be executed, it will call the method() method of
the Derived () class because the reference variable obj is pointing towards the
object of class Derived ().

public static void main(String[] args) {


//Base obj = new Base(); // Allowed
//Derived obj = new Derived(); // Allowed
// [Link]();
Base obj = new Derived(); // Yes it is allowed
//Derived obj2 = new Base(); // Not allowed
obj.method1();
obj.method2();
// obj.method3(); // Derived class method Not Allowed
}
}

• Java instanceof operaotor or method:-


• The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
• The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with
any variable that has null value, it returns false.
Code:-
23

Output:-

• Downcasting without the use of java instanceof:-


Downcasting can also be performed without the use of instanceof operator as displayed in the
following code:-
Abstraction:-
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.
Abstraction lets you focus on what the object does instead of how it does it.
Data binding : Data binding is a process of binding the application UI and business logic. Any
change made in the business logic will reflect directly to the application UI.
Abstraction is achieved in 2 ways :-
- Abstract class.
- Interfaces (Pure Abstraction).
- Abstract vs Interface.
24 What does Abstract mean?
Abstract in English means existing in through or as an idea without concrete existence.
• Abstract Class:-
1. An abstract class must be declared with an abstract keyword.
2. It can have abstract and non-abstract methods.
3. It cannot be instantiated.
4. It can have constructors and static methods also.
5. Abstract class are used when we want to achieve security & abstraction(hide certain details &
show only necessary details to the user)
6. It can have final methods which will force the subclass not to change the body of the method.
• Abstract method :
• A method that is declared without implementation is known as the abstract
method.
• An abstract method can only be used inside an abstract class.
• The body of the abstract method is provided by the class that inherits the
abstract class in which the abstract method is present.

● public abstract class phone Model {


● abstract void switch off ();
● || more code
● }

Code :-
25

Output:-

• Abstract class having constructor, data member and methods:-


An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
Code:- Using parametric constructor in both class parent abstract class and the derived class. Using
super( ) method to access both constructor.

Output:-
26

● Interfaces
● All the fields in interfaces are public, static and final by default.
● All methods are public & abstract by default.
● A class that implements an interface must implement all the methods declared in the
interface( which is abstract by nature).
● Just like a class in java is a collection of the related methods, an interface in java is a
collection of abstract methods.
● The interface is one more way to achieve abstraction in Java.
● An interface may also contain constants, default methods, and static methods.
● All the methods inside an interface must have empty bodies except default methods and
static methods.
● We use the interface keyword to declare an interface.
● There is no need to write abstract keyword before declaring methods in an interface
because an interface is implicitly abstract.
● An interface cannot contain a constructor (as it cannot be used to create objects)
● In order to implement an interface, java requires a class to use the implement keyword.
● Interfaces support the functionality of multiple inheritance.
● Java Interface also represents the IS-A relationship.
The relationship between classes and interfaces:-
• The relationship between class and interface:-
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Simple Examples of interface implements by class.


Diagram:-

Output-
27

Outputs:-

• Multiple inheritance in Java by interface:-


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.
Code:-
28

}
Output:-
29

• Is multiple inheritance allowed in Java?


• Multiple inheritance faces problems when there exists a method with the
same signature in both the superclasses.
• Due to such a problem, java does not support multiple inheritance directly, but
the similar concept can be achieved using interfaces.
• A class can implement multiple interfaces and extend a class at the same
time.
Some Important points :
1. Interfaces in java are a bit like the class but with a significantly different.
2. An Interface can only have method signatures field and a default method.
3. The class implementing an interface needs to declare the methods ( not field )
4. You can create a reference of an interface but not the object
5. Interface methods are public by default
• Default methods In Java:-
• An interface can have static and default methods.
• Default methods enable us to add new functionality to existing interfaces.
• This feature was introduced in java 8 to ensure backward compatibility while
updating an interface.
• A class implementing the interface need not implement the default methods.
• Interfaces can also include private methods for default methods to use.
• You can easily override a default method like any other method of an interface.
Another Example:-
interface Animal{
// Default method
default void say(){
[Link]("Hello, this is default method");
}
// Abstract method
void bark();
}
public class CWH implements Animal{

@Override
public void bark() {
[Link]("Dog barks!");
}
public static void main(String[] args) {
CWH obj1 = new CWH();
[Link]();
[Link]();
}}
Another Example:-
package [Link];
30 interface MyCamera{
void takeSnap();
void recordVideo();
private void greet(){
[Link]("Good Morning");
}
default void record4KVideo(){
greet();
[Link]("Recording in 4k...");
}}
interface MyWifi{
String[] getNetworks();
void connectToNetwork(String network);
}
class MyCellPhone{
void callNumber(int phoneNumber){
[Link]("Calling "+ phoneNumber);
}
void pickCall(){
[Link]("Connecting... ");
}}
class MySmartPhone extends MyCellPhone implements MyWifi, MyCamera{
public void takeSnap(){
[Link]("Taking snap");
}
public void recordVideo(){
[Link]("Taking snap");
}
// public void record4KVideo(){
// [Link]("Taking snap and recoding in 4k");
// }
public String[] getNetworks(){
[Link]("Getting List of Networks");
String[] networkList = {"Harry", "Prashanth", "Anjali5G"};
return networkList;}
public void connectToNetwork(String network){
[Link]("Connecting to " + network);
}}
public class cwh_57_default_methods {
public static void main(String[] args) {
MySmartPhone ms = new MySmartPhone();
ms.record4KVideo();
// [Link](); --> Throws an error!
String[] ar = [Link]();
for (String item: ar) {
[Link](item);
} }}
• Inheritance in Interfaces
Interfaces can extend other interfaces as shown below :

public interface Interface 1 {


void meth1 (); }
public interface Interface 2 extends Interface 1 {
31
void meth 2( ); }

Note: Remember that interface cannot implement another interface only classes can do that!
But the interface can be Extends by using the “extends” Keyword .

• Polymorphism in Interfaces
• GPS g = new Smartphone ( ); can only use GPS method
Smartphones = new Smartphone ( ); can only use smartphone methods
• Implementing an Interface force method implementation
Code:-
32
33 ● Java Tutorial: Abstract Classes Vs Interfaces
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

• Interpreted vs Compiled Languages:-


• Interpreter Vs Compliler : -
The interpreter translates one statement at a time into machine code. On the other hand, the
compiler scans the entire program and translates the whole of it into machine code
• Interpreter :-
1. one statement at a time
2. An interpreter is needed every time
3. Partial execution if an error occurs in the program.
4. Easy for programmers.
• Compiler :-
1. Entire program at a time
2. Once compiled, it is not needed
3. No execution if an error occurs
4. Usually not as easy as interpreted once
• Is Java interpreted or compiled?
Java is a hybrid language both compiled as well as interpreted.

• A JVM can be used to interpret this bycode.


• This bytecode can be taken to any platform ( win/ mac / Linux ) for education.
34
• Hence java is platform-independent ( write once run everywhere ).
• Executing a java program
java Uday java - compiles.
java Uday class - Interpreted .
• Encapsulation :-
Encapsulation is the process of combining data and functions into a single unit called class. In
Encapsulation, the data is not accessed directly; it is accessed through the functions present inside
the class. In simpler words, attributes of the class are kept private and public getter and setter
methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of
data hiding possible.(Data hiding: a language feature to restrict access to members of an object,
reducing the negative effect due to dependencies. e.g. "protected", "private" feature in Java).
• Packages in Java:-
• 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..

• Using a java package :


Import keyword is used to import packages in the java program. Example :
• Import java. Lang. * - import
• import [Link]. string - import string from java long
• s= new java long string ( "uday" ) - use without importing .
code:-
1. import [Link];
importing package should be create without the public static void main(String[ ] args ) and the
class in which we import the package have the public static void main(String[ ] args ) .
class which is used to import:-
35

Class in which the package is impoerted:-

Output:-

How to access package from another package?


There are three ways to access the package from outside the package.
• import package.*;
• import [Link];
• fully qualified name.
1) Using packagename.* :-
Code:-
Make a Class EMployeeID which is extends in the another class EmployeeNAME:-

Now the main class name Package_in_extended_class in which import both the
classes using import package.*;
In this the ID is protected because protected access modifiers can be pass through the same
package but if the ID is private it cannot be accessed.
36

Output:-

Note: Sequence of the program must be package then import then class.

Subpackage in java.
Package inside the package is called the subpackage. It should be created to categorize the
package further.
• Access Modifiers in Java:-
Access modifiers determine whether other classes can use a particular field or invoke a particular
method can be public, private, protected, or default ( no modifier ). See the table given below :
Access Modifier within class within package outside package by subclass only outside package
public Y Y Y Y
protected Y Y Y N
Default Y Y N N
private Y N N N
• Encapsulation in Java:-
Encapsulation in Java is a process of wrapping code and data together into a single unit , for
example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the class private.
Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
37
• Advantage of Encapsulation in Java:-
• By providing only a setter or getter method, you can make the class read-only or write-only.
In other words, you can skip the getter or setter methods.
• It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.
• 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.
Note:- In the encapsulation the private datatypes is can be access by the getter() and the setter()
Method:-
Awesome example of using getter( ) and the setter( ) methods:-
We using the two interface Interface_student_2 and Interface_student_1in the java and
implements in the class-public class Combining_interfaces_Student_1_2
implements Interface_student_1,Interface_student_2 in the same package .
Then the package is imported in the different class public class
package_in_interfaces_student of the different package which is in same project folder
name as the Encapsulation in java.
➢ From the package package_in_example:-
❖ Interface 1:-

❖ Interface-2:- project is lookalike this:-

❖ Combining the both interface :-


38

❖ Now calling the class in the different class which is in different package:-

Output:-
39

➢ Go check out my LinkedIn profile for more notes and other resources content

@Uday Sharma
mrudaysharma4600@[Link]
[Link]

You might also like