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

Chapter 2-4 Oop

The document discusses Java programming basics including data types, variables, operators, control statements and decision making statements. It describes the different types of variables, data types, operators and control statements like if, else-if and switch case that are used to control program flow in Java.

Uploaded by

adisuadmasu42
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 2-4 Oop

The document discusses Java programming basics including data types, variables, operators, control statements and decision making statements. It describes the different types of variables, data types, operators and control statements like if, else-if and switch case that are used to control program flow in Java.

Uploaded by

adisuadmasu42
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 128

Chapter two

Basic java programming


Data type
 Data types specify the different sizes and values that can be

stored in the variable.


 There are two types of data types in Java:

1. Primitive data types: The primitive data types include

boolean, char, byte, short, int, long, float and double.

2. Non-primitive data types: The non-primitive data types

include Classes, Interfaces, and Arrays.

2 04/25/2024
 In Java language, primitive data types are the building

blocks of data manipulation. These are the most basic data


types available in Java language.

3 04/25/2024
4 04/25/2024
Cont’d…

5 04/25/2024
Variables in java
 A variable is a container which holds the value while

the Java program is executed.


 A variable is assigned with a data type.

 Variable is a name of memory location.

 There are three types of variables in java: local, instance

and static.

6 04/25/2024
Cont’d…
Local variable

 Local variables are declared in methods, constructors, or

blocks.
 You can use this variable only within that method and the

other methods in the class aren't even aware that the


variable exists.
 A local variable cannot be defined with "static" keyword.

7 04/25/2024
Cont’d…
Instance variable:

 A variable declared inside the class but outside the body of

the method, is called an instance variable. It is not declared


as static.
 It is called an instance variable because its value is

instance-specific and is not shared among instances.

8 04/25/2024
Cont’d…
Static variables:
 A variable that is declared as static key word is.

 It cannot be local.

 You can create a single copy of the static variable and share it

among all the instances of the class.


 Memory allocation for static variables happens only once when

the class is loaded in the memory.

9 04/25/2024
Example
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12.}//end of class

10 04/25/2024
Sr. No. Local variables Instance variables Static variables

1. Variables declared An instance Static variables are


within a method variable is declared inside a
are local variables. declared inside a class but outside of
class but outside of a method starting
any method or with a keyword
block. static.

2. The scope of the An instance The static variable


local variable is variable is is accessible
limited to the accessible throughout the
method it is throughout the class.
declared inside. class.

11 04/25/2024
Cont’d…
3. A local variable starts its The object associated with The static variable has the
lifetime when the method the instance variable same lifetime as the
is invoked. decides its lifetime. program.

4. Local variable is Instance variable has Static variables only have


accessible to all the different copies for one single copy of the
objects of the class. different objects. entire class.

5. Used to store values that Used to store values that Used for storing constants.
are required for a are needed to be accessed
particular method. by different methods of
the class.

12 04/25/2024
Comments
 Comments make your code easy to understand, modify, and use.

 COMMENT STYLE #1: /* Comments here... */ . This style of

commenting comes to us directly from C.


 COMMENT STYLE #2: // Comment here... . This style of

commenting is borrowed from C++.


 COMMENT STYLE #3: /** Doc Comment here... */ uses these

comments to construct HTML documentation files that describe


your packages, classes, and methods as well as all the variables
they use.
13 04/25/2024
Identifiers
 All Java components require names. Names used for classes, variables, and

methods are called identifiers.


 All identifiers should begin with a letter (A to Z or a to z), currency

character ($) or an underscore (_).


 After the first character, identifiers can have any combination of characters.

 A key word cannot be used as an identifier.

 Most importantly, identifiers are case sensitive.

 Examples of legal identifiers: age, $salary, _value, __1_value.

14  Examples of illegal identifiers: 123abc, -salary. 04/25/2024


Operators

15 04/25/2024
Relational operator
Is equal to ==
Not equal to !=
Greater than >
Greater than or equal to >=
Less than <
Less than or equal to <=

16 04/25/2024
Logical operator

17 04/25/2024
Assignment operator

18 04/25/2024
Control statements
 Java compiler executes the code from top to bottom.

 The statements in the code are executed according to the

order in which they appear.


 However, Java provides statements that can be used to

control the flow of Java code.


 Such statements are called control flow statements.

 It is one of the fundamental features of Java, which

provides a smooth flow of program.


19 04/25/2024
Cont’d…
1. Decision Making statements

1. if statements

2. switch statement

2. Loop statements

1. do while loop

2. while loop

3. for loop

4. for-each loop
20 04/25/2024
cont’d…
1. Jump statements

1. break statement

2. continue statement

21 04/25/2024
Decision making statements
 As the name suggests, decision-making statements decide

which statement to execute and when.


 Decision-making statements evaluate the Boolean

expression and control the program flow depending upon


the result of the condition provided.
 There are two types of decision-making statements in Java,

i.e., If statement and switch statement.

22 04/25/2024
Cont’d…
If Statement:
 In Java, the "if" statement is used to evaluate a condition.

 The control of the program is diverted depending upon the

specific condition.
 The condition of the If statement gives a Boolean value,

either true or false.


 In Java, there are four types of if-statements given below.

23 04/25/2024
Cont’d…
Simple if statement:
It is the most basic statement among all control flow
statements in Java.
It evaluates a Boolean expression and enables the
program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.

24 04/25/2024
25 04/25/2024
Cont’d..
example
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
26 04/25/2024
Cont’d…
if-else statement
 The if-else statement is an extension to the if-statement,

which uses another block of code, i.e., else block.


 The else block is executed if the condition of the if-block is

evaluated as false.

27 04/25/2024
28 04/25/2024
Cont’d…
example
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10.}
11.}

29 04/25/2024
Cont’d…
 if-else-if ladder:

 The if-else-if statement contains the if-statement followed

by multiple else-if statements.


 In other words, we can say that it is the chain of if-else

statements that create a decision tree where the program


may enter in the block of code where the condition is true.
 We can also define an else statement at the end of the

chain.
30 04/25/2024
31 04/25/2024
Cont’d…
example
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }

32 04/25/2024
Cont’d….
Nested if-statement
 In nested if-statements, the if statement can contain

a if or if-else statement inside another if or else-if


statement.

33 04/25/2024
Cont’d…

34 04/25/2024
Cont’d….
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }

35 04/25/2024
Switch Statement:
 In Java, Switch statements are similar to if-else-if
statements.
 The switch statement contains multiple blocks of code

called cases and a single case is executed based on the


variable which is being switched.
 The switch statement is easier to use instead of if-else-if

statements.
 It also enhances the readability of the program.

36 04/25/2024
Cont’d…
• The case variables can be int, short, byte, char, or

enumeration. String type is also supported since version 7


of Java
• Cases cannot be duplicate

• Default statement is executed when any of the case doesn't

match the value of expression. It is optional.


• The value for a case must be the same data type as the

variable in the switch and it must be a constant or a literal.


37 04/25/2024
Cont’d..
• Break statement terminates the switch block when the

condition is satisfied.
• It is optional, if not used, next case is executed.

• While using switch statements, we must notice that the case

expression will be of the same type as the variable.


• However, it will also be a constant value.

38 04/25/2024
39 04/25/2024
Cont’d…
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }

40 04/25/2024
Reptation statement
 In programming, sometimes we need to execute the block

of code repeatedly while some condition evaluates to true.


 However, loop statements are used to execute the set of

instructions in a repeated order.


 The execution of the set of instructions depends upon a

particular condition.
 In Java, we have three types of loops that execute similarly.

 However, there are differences in their syntax and condition


41 04/25/2024
checking time.
Cont’d…
Java for loop

 In Java, for loop is similar to C and C++.

 It enables us to initialize the loop variable, check the

condition, and increment/decrement in a single line of


code.
 We use the for loop only when we exactly know the

number of times, we want to execute the block of code.

42 04/25/2024
43 04/25/2024
Cont’d…
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
example
4. public class Calculattion {
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. int sum = 0;
8. for(int j = 1; j<=10; j++) {
9. sum = sum + j;
10.}
11. System.out.println("The sum of first 10 natural numbers is " + sum);
12.}
13.}

44 04/25/2024
 Java for-each loop

 Java provides an enhanced for loop to traverse the data

structures like array or collection.


 In the for-each loop, we don't need to update the loop variable.

 The syntax to use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

45 04/25/2024
Cont’d…
example
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\
n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10.}
46 04/25/2024
Cont’d…
 Java while loop

 The while loop is also used to iterate over the number of

statements multiple times.


 However, if we don't know the number of iterations in advance, it

is recommended to use a while loop.


 Unlike for loop, the initialization and increment/decrement

doesn't take place inside the loop statement in while loop.


1. while(condition){
2. //looping statements

47
3. } 04/25/2024
Cont’d…

48 04/25/2024
Cont’d..
example
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10.}
11.}

49 04/25/2024
cont’d…
 Java do-while loop

 The do-while loop checks the condition at the end of the loop after

executing the loop statements.


 When the number of iteration is not known and we have to execute

the loop at least once, we can use do-while loop.


 It is also known as the exit-controlled loop since the condition is not

checked in advance.
1. do
2. {
3. //statements
4. } while (condition);

50 04/25/2024
Cont’d….

51 04/25/2024
Cont’d…
Example
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10.}
11.}

52 04/25/2024
Jump Statements

 Jump statements are used to transfer the control of the

program to the specific statements.


 In other words, jump statements transfer the execution

control to the other part of the program.


 There are two types of jump statements in Java, i.e., break

and continue.

53 04/25/2024
Cont’d…
Java break statement
 As the name suggests, the break statement is used to break

the current flow of the program and transfer the control to


the next statement outside a loop or switch statement.
 However, it breaks only the inner loop in the case of the

nested loop.
 Can not stated independently, it can only be written inside

the loop or switch statement.


54 04/25/2024
Cont’d…
Example
1. public class BreakExample {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. for(int i = 0; i<= 10; i++) {
5. System.out.println(i);
6. if(i==6) {
7. break;
8. }
9. }
10.}
11.}

55 04/25/2024
Cont’d….
 Java continue statement

 Unlike break statement, the continue statement doesn't

break the loop, whereas, it skips the specific part of the


loop and jumps to the next iteration of the loop
immediately.

56 04/25/2024
Cont’d…
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }

57 04/25/2024
Chapter Three
Objects and Classes in Java
 Class- A class can be defined as a template/blueprint that describes the

behavior/state that the object of its type support.


 Object − Objects have states and behaviors. Example: A dog has states -

color, name, breed as well as behaviors – wagging the tail, barking, eating.
An object is an instance of a class
 Java provides a reserved keyword class to define a class.

 The keyword must be followed by the class name.

 Inside the class, we declare methods and variables

58 04/25/2024
Class
 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 can't be physical.
 A class in Java can contain:

• Fields

• Methods

• Constructors

• Blocks

• Nested class and Interfaces

59 04/25/2024
Cont’d….
 Instance variable in Java

 A variable which is created inside the class but outside the method is known as an

instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known
as an instance variable.

60 04/25/2024
Class declaration
 In general, class declaration includes the following in the order as it
appears:
1. Modifiers: A class can be public or has default access.
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized
by convention).
4. Superclass (if any): The name of the class's parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
5. Interfaces (if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.

61 04/25/2024
The General Form of a Class
 A class is declared by use of the class keyword.

class <class_name>{
field;
method;
}
 The data, or variables, defined within a class are called instance

variables.
 The code is contained within methods. Collectively, the methods

and variables defined within a class are called members of the class

62 04/25/2024
object
 An object in Java is the physical as well as a logical entity, whereas,

a class in Java is a logical entity only.

An object has three characteristics:


• State: represents the data (value) of an object.

• Behavior: represents the behavior (functionality) of an object such

as deposit, withdraw, etc.


• Identity: An object identity is typically implemented via a unique

ID. The value of the ID is not visible to the external user. However,
it is used internally by the JVM to identify each object uniquely.
63 04/25/2024
Cont’d
 Object and Class Example:

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

64 04/25/2024
Creating methods and constructor in side the class
 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.

 It also provides the easy modification

 readability of code, just by adding or removing a chunk of code. The

method is executed only when we call or invoke it.


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

65 04/25/2024
Method Declaration

66 04/25/2024
cont’d…
 Method Signature: Every method has a method signature. It is a part of the method

declaration. It includes the method name and parameter list.


 Access Specifier/modifier: Access specifier or modifier is the access type of the method.

It specifies the visibility of the method. Java provides four types of access specifier:

• Public: The method is accessible by all classes when we use public specifier in our

application.

• Private: When we use a private access specifier, the method is accessible only in the

classes in which it is defined.

• Protected: When we use protected access specifier, the method is accessible within

the same package or subclasses in a different package.

• Default: When we do not use any access specifier in the method declaration, Java
67 04/25/2024
uses default access specifier by default. It is visible only from the same package only.
Cont’d…
 Return Type: Return type is a data type that the method returns. It may have a

primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
 Method Name: It is a unique name that is used to define the name of a method.

It must be corresponding to the functionality of the method. Suppose, if we are


creating a method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
 Parameter List: It is the list of parameters separated by a comma and enclosed

in the pair of parentheses. It contains the data type and variable name. If the
method has no parameter, left the parentheses blank.
 Method Body: It is a part of the method declaration. It contains all the actions

68 to be performed. It is enclosed within the pair of curly 04/25/2024


braces.
Naming a Method
 While defining a method, remember that the method name must be

a verb and start with lowercase letter.


 If the method name has more than two words, the first name must be a

verb followed by adjective or noun.


 In the multi-word method name, the first letter of each word must be

in uppercase except the first word.


 Example:

 Single-word method name: sum(), area()

 Multi-word method name: areaOfCircle(), stringComparision()

69 04/25/2024
Types of Method
 There are two types of methods in Java:

• Predefined Method

• User-defined Method

Predefined Method
 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.

70 04/25/2024
Cont’d…
 When we call any of the predefined methods in our program, a series of

codes related to the corresponding method runs in the background that is


already stored in the library.

Example:
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
71 04/25/2024
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.

72 04/25/2024
Return type
 A return statement causes the program control to transfer

back to the caller of a method.


 Every method in Java is declared with a return type and it

is mandatory for all java methods.


 A return type may be a primitive type like int, float,

double, a reference type or void type(returns nothing).

73 04/25/2024
Cont’d…

74 04/25/2024
Cont’d…

75 04/25/2024
constructor
 A constructor initializes an object immediately upon creation.

 It has the same name as the class in which it resides and is syntactically

similar to a method.
 Once defined, the constructor is automatically called immediately after

the object is created, before the new operator completes.


 Constructors look a little strange because they have no return type, not

even void.
 This is because the implicit return type of a class’ constructor is the

class type itself.

76 04/25/2024
Cont’d…
 Every time an object is created using the new() keyword, at least one

constructor is called.
 It calls a default constructor if there is no constructor available in the

class. In such case, Java compiler provides a default constructor by


default.

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

77 04/25/2024
Default constructor
//Java Program to create and call a default constructor
class memory{
//creating a default constructor
memory(){System.out.println(“is memorized");}
//main method
public static void main(String args[]){
//calling a default constructor
memory b=new memory();
}
}

78 04/25/2024
Parametrized constructor
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
79
} 04/25/2024
}
Cont’d…
 Ways to initialize object
 There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor

80 04/25/2024
Cont’d
 Object and Class Example: Initialization through reference
 Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference variable.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
//printing members with a white space
}
}81 04/25/2024
Cont’d
We can also create multiple objects and store information in it through reference
variable.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name=“Aster";
s2.id=102;
s2.name=“Abebe";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
82 04/25/2024
}
Cont’d…
Object and Class Example: Initialization through method
 In this example, we are creating the two objects of Student class and

initializing the value to these objects by invoking the insertRecord


method. Here, we are displaying the state (data) of the objects by
invoking the displayInformation() method

83 04/25/2024
Cont’d
class Student{
int Stud_id;
String name;
void insertRecord(int r, String n){
Stud_Id=r;
name=n;
}
void displayInformation()
{
System.out.println(Stud_id+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(“DTU00/tech2015”,“Aster");
s2.insertRecord(“DTU01/tech2015”,“Abebe");
s1.displayInformation();
s2.displayInformation();
84 } 04/25/2024
}
Cont’d
 Object and Class Example: Initialization through a constructor

class Student{
int Stud_id;
String name;
Student(int r, String n){
Stud_Id=r;
name=n;
}
void displayInformation()
{
System.out.println(Stud_id+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1. Student(“DTU00/tech2015”,“Aster");
s2. Student(“DTU01/tech2015”,“Abebe");
s1.displayInformation();
s2.displayInformation();
}85 04/25/2024
}
Java Modifier Types
Modifiers are keywords that you add to those
definitions to change their meanings.
has a wide variety of modifiers, including the
following:
 Java Access Modifiers
 Non Access Modifiers(reading assignment)

86 04/25/2024
Java Access Modifiers
Java provides a number of access modifiers to set
access levels for classes, variables, methods, and
constructors. The four access levels are:
Visible to the package, the default. No modifiers are
needed.
Visible to the class only (private).
 Visible to the world (public).
Visible to the package and all subclasses (protected).

87 04/25/2024
Cont’d…
Access within class within outside outside
Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

88 04/25/2024
private
package pack;
class A{
private int data=40; );//private instance variable
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
89 04/25/2024
Private constructor
package pack;
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

90 04/25/2024
Default Access Modifier - No Keyword
package pack;
class A{
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();//Compile Time Error
obj.msg();//Compile Time Error
}
}
91 04/25/2024
protected
 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. It can't be applied on the class.

92 04/25/2024
Cont’d…
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();
}
}
93 04/25/2024
Public
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();
94
} 04/25/2024
}
95 04/25/2024
interface
 An interface in Java is a blueprint of a class. It has static constants

and abstract methods.


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

96 04/25/2024
Cont’d…

97 04/25/2024
Instance
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}

98 04/25/2024
Chapter four
Chap 4 Object Oriented
Programming Concepts
"Inheritance"
 Java – Inheritance : Inheritance can be defined as the

process where one class acquires the properties (methods


and fields) of another.
 creating 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.


 you can add new methods and fields in your current class also.

 In inheritance the most commonly used keyword would be


99 04/25/2024
extends and implements.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can
be achieved).
• For Code Reusability.

100 04/25/2024
Cont’d…
Syntax:
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

101 04/25/2024
102 04/25/2024
Cont’d…
 Eg.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

103 04/25/2024
keywords
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.

104 04/25/2024
Cont’d…
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}

105 04/25/2024
Cont’d…
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}

106 04/25/2024
Cont’d…
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10.class TestSuper3{
11.public static void main(String args[]){
12.Dog d=new Dog();
13.}}
107 04/25/2024
Cont’d…
Instance of:
Used to check the subclass is actually in super class
public class Animal {

} class Mammal extends Animal { }


class Reptile extends Animal {
}
class Dog extends Mammal{ public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(a instanceof Dog);
System.out.println(d instanceof Animal);
System.out.println(d instanceof Dog);
}
108 04/25/2024
}
IS - A Relationship
 mechanism in which one object acquires all the properties

and behaviors of a parent object.


 With the use of the extends keyword, the subclasses will

be able to inherit all the properties of the super class


except for the private properties of the super class.
 From the above instance of example

 Mamal IS-A Animal

 Dog IS-A Animal

109 04/25/2024
HAS - A relationship
 These relationships are mainly based on the usage.

 This determines whether a certain class HAS-A certain thing.

 This relationship helps to reduce duplication of code as well as bugs.

 If a class have an entity reference, it is known as Aggregation.

 For example, Employee object contains many information's such as

id, name, emailId etc.


 It contains one more object named address, which contains its own

information's such as city, state, country, zipcode etc. as given

110 below. 04/25/2024


Cont’d…
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }

7. public class Address {


8. String city,state,country;
9.
10. public Address(String city, String state, String country) {
11. this.city = city;
12. this.state = state;
13. this.country = country;
111 04/25/2024
14. }
cont’d…
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5. public Emp(int id, String name,Address address) {
6. this.id = id;
7. this.name = name;
8. this.address=address;
9. }
10.
112 04/25/2024
Cont’d…
1. void display(){
2. System.out.println(id+" "+name);
3. System.out.println(address.city+" "+address.state+" "+address.country);
4. }
5. public static void main(String[] args) {
6. Address address1=new Address("gzb","UP","india");
7. Address address2=new Address("gno","UP","india");
8.
9. Emp e=new Emp(111,"varun",address1);
10.Emp e2=new Emp(112,"arun",address2);
11.
12.e.display();
13.e2.display();
14.
113 15.} 04/25/2024
Cont’d…
Why use Aggregation?
• For Code Reusability.

114 04/25/2024
Types of Inheritance
 On the basis of class, 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.

115 04/25/2024
Cont’d…

116 04/25/2024
Single level Inheritance
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}

117 04/25/2024
Multilevel Inheritance
Eg.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat(); 04/25/2024
118
16. }}
Hierarchical inheritance
Eg.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();

119 04/25/2024
Java Polymorphism
 is the ability of an object to take on many forms.

 The most common use of polymorphism in OOP occurs when

a parent class reference is used to refer to a child class object.


Polymorphism in Java has two types:

– Compile time polymorphism (static binding) and


– Runtime polymorphism (dynamic binding).

 Method overloading is an example of static polymorphism, while method


overriding is an example of dynamic polymorphism.

120 04/25/2024
Cont’d….
 Method overriding:

 If subclass (child class) has the same method as declared

in the parent class


 If a subclass provides the specific implementation of the

method that has been declared by one of its parent class.


• Method overriding is used to provide the specific
implementation of a method which is already provided
by its superclass.
• Method overriding is used for runtime polymorphism

121 04/25/2024
Cont’d…
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.
3. There must be an IS-A relationship (inheritance).

122 04/25/2024
Cont’d…
Eg.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }

123 04/25/2024
Cont’d…
Method Overloading in Java
If a class has multiple methods having same name but
different in parameters
Method overloading increases the readability of the
program
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

124 04/25/2024
Cont’d…
 Method Overloading: changing no. of arguments
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
125 04/25/2024
Cont’d…
 Method Overloading: changing data type of
arguments
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
126 04/25/2024
Cont’d…

127 04/25/2024
128 04/25/2024

You might also like