0% found this document useful (0 votes)
2 views10 pages

Introduction to OOP in Java Basics

This document provides an introduction to Object-Oriented Programming (OOP) in Java, covering key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It also explains the Java execution process, control flow statements, input/output functions, and the use of packages. Additionally, it includes code examples to illustrate the concepts discussed.

Uploaded by

swarooprawool006
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)
2 views10 pages

Introduction to OOP in Java Basics

This document provides an introduction to Object-Oriented Programming (OOP) in Java, covering key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It also explains the Java execution process, control flow statements, input/output functions, and the use of packages. Additionally, it includes code examples to illustrate the concepts discussed.

Uploaded by

swarooprawool006
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

Module 1(Introduction to OOP in Java )

1 Introduction (Java)
Java is a high-level, platform-independent, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle) in 1995.
It is designed to have fewer implementation dependencies, and its slogan is ”Write Once, Run Any-
where” (WORA), thanks to the Java Virtual Machine (JVM).
Execution of Java Program
• Source Code (.java) Human-readable code written by the programmer.
• Compiler (javac) Converts .java into .class bytecode. Bytecode is platform-independent.

• Class Loader Loads compiled .class files into memory.


• Bytecode Verifier Ensures no harmful instructions are present.
• Java Virtual Machine (JVM) Executes bytecode using Just-In-Time (JIT) compilation. Converts
bytecode to machine code for the specific OS/CPU.

[Link] [Compiler] [Link] [Interpreter/JVM] Output

2 Classes and Objects


In Java, Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
objects and classes.

2.1 Class
A class is a blueprint or template for creating objects. It defines properties (fields) and behaviors
(methods).
Syntax:
1 class Car {
2 // fields ( attributes )
3 String color ;
4 int speed ;
5
6 // method ( behavior )
7 void drive () {
8 System . out . println ( " The car is driving . " ) ;
9 }
10 }

2.2 Object
An object is an instance of a class. It is created using the new keyword.
Syntax:

1
1 public class Main {
2 public static void main ( String [] args ) {
3 // Creating an object of the Car class
4 Car myCar = new Car () ;
5
6 // Accessing fields and methods
7 myCar . color = " Red " ;
8 myCar . speed = 100;
9 myCar . drive () ;
10 }
11 }

Explanation:
• Car myCar = new Car(); → Creates an object myCar of class Car.
• [Link] = ”Red”; → Sets the color field of the object.

• [Link](); → Calls the drive method of the object.

2.3 Message Passing


Message Passing in Java refers to the process by which objects communicate with each other by invoking
methods. It is a core concept in Object-Oriented Programming (OOP), enabling encapsulation and
modular design.
In Java, message passing is done via method calls between objects.
For example:
1 class Person {
2 void sayHello () {
3 System . out . println ( " Hello ! " ) ;
4 }
5 }
6
7 public class Main {
8 public static void main ( String [] args ) {
9 Person p = new Person () ; // Object creation
10 p . sayHello () ; // Message passing ( method invocation )
11 }
12 }

Explanation:

• [Link](); — Here, object p receives a message (sayHello) and responds by executing the method.
• This simulates the idea of “sending a message to an object.”

3 Branching and Looping in Java


Java provides control flow statements that enable decision making and repetition in a program. These
are divided into two main categories:

3.1 Branching (Decision Making)


Branching allows the program to choose between different paths of execution based on conditions.

3.1.1 if statement

1 int a = 10;
2 if ( a > 5) {
3 System . out . println ( " a is greater than 5 " ) ;
4 }

2
3.1.2 if-else statement

1 if ( a % 2 == 0) {
2 System . out . println ( " Even " ) ;
3 } else {
4 System . out . println ( " Odd " ) ;
5 }

3.1.3 if-else ladder

1 if ( a > 0) {
2 System . out . println ( " Positive " ) ;
3 } else if ( a < 0) {
4 System . out . println ( " Negative " ) ;
5 } else {
6 System . out . println ( " Zero " ) ;
7 }

3.1.4 switch statement

1 int day = 2;
2 switch ( day ) {
3 case 1:
4 System . out . println ( " Monday " ) ;
5 break ;
6 case 2:
7 System . out . println ( " Tuesday " ) ;
8 break ;
9 default :
10 System . out . println ( " Other day " ) ;
11 }

3.2 Looping (Iteration)


Looping allows executing a block of code repeatedly under certain conditions.

3.2.1 for loop

1 for ( int i = 1; i <= 5; i ++) {


2 System . out . println ( i ) ;
3 }

3.2.2 while loop

1 int i = 1;
2 while ( i <= 5) {
3 System . out . println ( i ) ;
4 i ++;
5 }

3.2.3 do-while loop

1 int i = 1;
2 do {
3 System . out . println ( i ) ;
4 i ++;
5 } while ( i <= 5) ;

3.2.4 Enhanced for loop (for arrays/collections)

1 int [] arr = {10 , 20 , 30};


2 for ( int num : arr ) {
3 System . out . println ( num ) ;
4 }

3
Table 1: Summary of Control Flow Statements
Type Statement Purpose
Branching if, if-else, switch Choose between paths
Looping for, while, do-while Repeat actions based on conditions

4 Java Class Structure: Data Members, Methods, and Con-


structors
4.1 Data Members
These are variables declared inside a class to store the state (properties) of an object.
1 class Car {
2 String color ; // data member
3 int speed ; // data member
4 }

4.2 Member Functions (Methods)


These are functions defined inside a class to perform operations or behavior on data members.
1 class Car {
2 String color ;
3 int speed ;
4
5 void drive () { // member function
6 System . out . println ( " Car is driving at " + speed + " km / h . " ) ;
7 }
8 }

4.3 Constructors
A constructor is a special method that is called automatically when an object is created. It has the same
name as the class and no return type.
1 class Car {
2 String color ;
3 int speed ;
4
5 // Constructor
6 Car ( String c , int s ) {
7 color = c ;
8 speed = s ;
9 }
10 }

Table 2: Types of Constructors


Type Description
Default Constructor Provided by Java if no constructor is defined
No-arg Constructor Constructor with no parameters
Parameterized Constructor Accepts parameters to initialize data
Copy Constructor (manually written) Copies values from another object (Java doesn’t provide it by default)

1 class Car {
2 String color ;
3 int speed ;
4
5 // No - arg constructor
6 Car () {
7 color = " Red " ;

4
8 speed = 100;
9 }
10
11 // Parameterized constructor
12 Car ( String c , int s ) {
13 color = c ;
14 speed = s ;
15 }
16
17 // Copy constructor
18 Car ( Car c ) {
19 color = c . color ;
20 speed = c . speed ;
21 }
22 }

4.4 Static Members and Functions


4.4.1 Static Data Members:
• Shared across all objects.
• Only one copy exists.

1 class Student {
2 static String college = " ABC College " ; // static data member
3 String name ;
4 }

4.4.2 Static Member Functions:


• Can access only static members.
• Called using the class name.

1 class Student {
2 static String college = " ABC College " ;
3
4 static void showCollege () { // static function
5 System . out . println ( college ) ;
6 }
7 }

5 The Pillars of OOP in Java


5.1 Inheritance
Definition: When a class (child or subclass) inherits properties and methods from another class (parent
or superclass).
Purpose: To promote code reusability and hierarchical classification.
Example:
1 class Animal {
2 void eat () {
3 System . out . println ( " This animal eats food . " ) ;
4 }
5 }
6
7 class Dog extends Animal {
8 void bark () {
9 System . out . println ( " Dog barks . " ) ;
10 }
11 }
12
13 public class Main {
14 public static void main ( String [] args ) {

5
15 Dog d = new Dog () ;
16 d . eat () ; // Inherited from Animal
17 d . bark () ; // Defined in Dog
18 }
19 }

5.2 Polymorphism
Definition: Ability of one interface or method to take many forms. It allows a single function to behave
differently based on the object calling it.

5.2.1 Compile-time Polymorphism (Method Overloading):


Same method name with different parameters.
1 class MathOperation {
2 int add ( int a , int b ) {
3 return a + b ;
4 }
5
6 double add ( double a , double b ) {
7 return a + b ;
8 }
9 }

5.2.2 Runtime Polymorphism (Method Overriding):


Subclass provides specific implementation of a method already defined in the parent class.
1 class Animal {
2 void sound () {
3 System . out . println ( " Animal makes sound " ) ;
4 }
5 }
6
7 class Cat extends Animal {
8 void sound () {
9 System . out . println ( " Cat meows " ) ;
10 }
11 }

5.3 Abstraction
Definition: Hiding internal implementation details and showing only essential features.
Achieved using:
1. Abstract classes
2. Interfaces
Abstract Class Example:
1 abstract class Shape {
2 abstract void draw () ;
3 }
4
5 class Circle extends Shape {
6 void draw () {
7 System . out . println ( " Drawing Circle " ) ;
8 }
9 }

5.4 Encapsulation
Definition: Wrapping of data (variables) and code (methods) together into a single unit (class) and
restricting access to the inner workings.
Achieved using: private fields and public getters/setters.
Example:

6
1 class Student {
2 private int age ; // Private variable
3
4 public void setAge ( int a ) {
5 age = a ;
6 }
7
8 public int getAge () {
9 return age ;
10 }
11 }

6 Input and Output Functions in Java


6.1 Output:
Used to display information to the user.
1 a ) System . out . print () -> System . out . print ( " Hello " ) ;

Prints text on the same line.


1 b ) System . out . println () -> System . out . println ( " Hello World " ) ;

Prints text and moves to the next line.

6.2 Input:
Used to take data from the user. Two common ways:

6.2.1 Scanner Class (Easy and Common)

1 import java . util . Scanner ;


2
3 public class InputExample {
4 public static void main ( String [] args ) {
5 Scanner sc = new Scanner ( System . in ) ;
6
7 System . out . print ( " Enter your name : " ) ;
8 String name = sc . nextLine () ;
9
10 System . out . print ( " Enter your age : " ) ;
11 int age = sc . nextInt () ;
12
13 System . out . println ( " Hello " + name + " , age : " + age ) ;
14 }
15 }

Table 3: Common Scanner Methods


Method Description
next() Reads one word
nextLine() Reads full line
nextInt() Reads integer
nextDouble() Reads double value
nextBoolean() Reads boolean

6.2.2 BufferedReader Class (Faster, but complex)


Need to import
1 import java . io . Buffere dReader ;
2 import java . io . I n p u t S t r e a m R e a d e r ;
3 import java . io . IOException ;

7
Example
1 import java . io .*;
2
3 public class B u f f e r e d R e a d e r E x a m p l e {
4 public static void main ( String [] args ) throws IOException {
5 Buff eredRead er br = new Bu fferedR eader ( new I n p u t S t r e a m R e a d e r ( System . in ) ) ;
6
7 System . out . print ( " Enter your name : " ) ;
8 String name = br . readLine () ;
9
10 System . out . print ( " Enter your age : " ) ;
11 int age = Integer . parseInt ( br . readLine () ) ;
12
13 System . out . println ( " Hello " + name + " , age : " + age ) ;
14 }
15 }

Notes:
• readLine() always returns a String
• Use [Link]() or [Link]() to convert input

7 Packages in JAVA
A package is a namespace that organizes a set of related classes and interfaces.
Benefits of Packages:
• Avoids naming conflicts
• Improves code modularity
• Allows controlled access
• Makes it easier to maintain and re-use code

Table 4: Types of Packages in Java


Type Description Example
Built-in Packages Predefined packages provided by Java SDK [Link], [Link], [Link]
User-defined Packages Custom packages created by the programmer mypackage, [Link]

Table 5: Some Common Built-in Packages


Package Purpose
[Link] Core classes (String, Math, etc.)
[Link] Utilities (Scanner, ArrayList, Date)
[Link] Input/Output (File, BufferedReader)
[Link] JDBC for database access
[Link] GUI components

7.1 Creating a User-defined Package


Step 1: Create the package
1 // File : MyClass . java
2 package mypackage ;
3
4 public class MyClass {
5 public void showMessage () {
6 System . out . println ( " Hello from mypackage ! " ) ;
7 }
8 }

8
Step 2: Compile with -d option
1 javac -d . MyClass . java

This creates a folder mypackage and places [Link] inside it.


Step 3: Use the package in another class
1 // File : TestPackage . java
2 import mypackage . MyClass ;
3
4 public class TestPackage {
5 public static void main ( String [] args ) {
6 MyClass obj = new MyClass () ;
7 obj . showMessage () ;
8 }
9 }

Step 4: Compile and run


1 javac TestPackage . java
2 java TestPackage

7.2 Package Naming Convention


Use reverse domain names to avoid name clashes:
1 package com . example . project . module ;

Table 6: Access Modifiers with Packages


Modifier Accessible within same package Accessible outside package
public Yes Yes
protected Yes(and in subclasses outside) Yes
(default) Yes No
private No No

8 Arrays and Vectors in JAVA


8.1 Arrays in Java
An array is a fixed-size, indexed collection of elements of the same data type.
Declaration and Initialization:
1 int [] arr = new int [5]; // Declaration with size
2 arr [0] = 10; // Assigning values
3
4 // OR directly initialize
5 int [] nums = {1 , 2 , 3 , 4 , 5};

Accessing Elements:
1 System . out . println ( nums [2]) ; // Output : 3

Loop through Array:


1 for ( int i = 0; i < nums . length ; i ++) {
2 System . out . println ( nums [ i ]) ;
3 }

8.2 Vectors in Java


A Vector is a dynamic array that can grow or shrink in size. It is part of the [Link] package.
Import Statement:
1 import java . util . Vector ;

Declaration and Initialization:

9
1 Vector < Integer > v = new Vector < >() ;
2 v . add (10) ;
3 v . add (20) ;

Accessing Elements:
1 System . out . println ( v . get (1) ) ; // Output : 20

Loop through Vector:


1
2 for ( int i = 0; i < v . size () ; i ++) {
3 System . out . println ( v . get ( i ) ) ;
4 }

Table 7: Key Differences: Array vs Vector


Feature Array Vector
Size Fixed Dynamic (auto-resizable)
Package [Link] (no import) [Link] (needs import)
Synchronization Not synchronized Synchronized (thread-safe)
Performance Faster (no overhead) Slightly slower (due to sync)
Generic Support No Yes (Vector<Integer>, etc.)

When to Use What?


• Use Array: When size is known in advance and performance is important.
• Use Vector: When size can change during execution and thread safety is needed.

Example Program Using Both:


1 import java . util . Vector ;
2
3 public class Main {
4 public static void main ( String [] args ) {
5 // Array
6 int [] arr = {1 , 2 , 3};
7 for ( int num : arr ) {
8 System . out . println ( " Array : " + num ) ;
9 }
10
11 // Vector
12 Vector < String > names = new Vector < >() ;
13 names . add ( " Alice " ) ;
14 names . add ( " Bob " ) ;
15 for ( String name : names ) {
16 System . out . println ( " Vector : " + name ) ;
17 }
18 }
19 }

10

You might also like