0% found this document useful (0 votes)
28 views11 pages

Oop Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

Name: Muhammad Ahsan khan Sap id:64084

Form Lecture: (01 to 07)

OOP THEORY ASSIGNMENT


Classes:
Definition: Classes in Java are blueprints for creating objects.
 They encapsulate data and behavior, promoting encapsulation, inheritance, polymorphism, and abstraction.
Classes enhance modularity, reusability, and code organization, ensuring efficient, readable, and maintainable
software.
Example: class class_name{}

Objects:
Definition: Objects in Java are instances of classes, representing real-world entities.
 They encapsulate data and behavior, allowing for modularity and reusability in code. Objects enable the
principles of OOP: encapsulation, inheritance, polymorphism, and abstraction. They enhance code
organization, readability, and maintainability, making complex systems manageable and adaptable.

1. Data field
2. Methods/Function
3. Construction //it can contain other things
4.
Example: className object = new className(); //any task perform will come in class

1) Class person {
String name;
int age;

void display Result(){


System.out.println(“Name: “ +name);
System.out.println(“Age: “ +age);
}
}

2) public class Main{


public Static void main(String[] args){

person P1=new person();


P1.name=”Ahsan”
P1.age=”20”
P1.display Result():

person P2=new person();


P2.name=”zaid”
P2.age=”21”
P2.display Result();
}
}
Types of Errors:
 Syntax Error: Violation of language grammar rules.
 Runtime Error: Occur during program execution due to unexpected conditions.
 Logical Error: Incorrect logic or algorithm producing unexpected results.
 Compilation Error: Arise during compilation due to syntax or type mismatches.
 Semantic Error: Code behaves differently from expectations despite being syntactically correct.
 Exception: Events disrupting normal program flow during execution.

Comments:
 Textual annotations in Java providing explanations within code, ignored by the compiler.

Primitive Data Type


There are 8th types
1. Integer // int age = 25
2. Boolean // True or False
3. Float // float = 52.65
4. Double // double = 56.6564
5. Long // long max or min = -9223372036854775808L to 9223372036854775807L
6. Short // short = -32,768 to 32,767
7. Byte // byte = -127 to 127
8. Character // char = ‘Ali’

Method and its Type


Definition: Any small table perform in the Class
Example:// Class declaration should be properly formatted

public class Main {

// Creating Attributes
int x = 10;
int age = 29;
String name = "Ali";

// Method with no arrangement


public void display_message() {
System.out.println("I am display message Method");
}

// A method with no arrangement


public void show_x_value() {
System.out.println("Value of x is " + x);
}

// A method with one arrangement of type int


public void display_number(int num) {
System.out.println("Value of the number is " + num);
}

// A method with one arrangement of type String


public void display_text(String msg) {
System.out.println("Message is " + msg);
}
// A method with return type int and no arrangement
public int get_age() {
return age;
}

// A method with return type String and no arrangement


public String get_value_name() {
return name;
}

// Method with return type int and two arrangements


public int add_number(int i, int j) {
int sum = i + j;
return sum;
}

public static void main(String[] args) {


// Create an object of class Main
Main m = new Main();

m.display_message();
m.show_x_value();
m.display_number(5);
m.display_text("Ali");

System.out.println("My name is " + m.get_value_name());


System.out.println("My age is " + m.get_age());
System.out.println("Sum of two numbers is " + m.add_number(2, 3));
}
}
Output:
 I am display message Method
 Value of x is 10
 Value of the number is 5
 Message is Ali
 My name is Ali
 My age is 29
 Sum of two numbers is 5

What is within class / inside class and outside class in java?

Inside Class in Java:

 Attributes/Fields/Variables: Declaration of variables that represent the state of objects.


 Methods/Functions: Functions defined within the class to perform specific tasks or operations.
 Constructors: Special methods used for initializing objects when they are created.
 Nested Classes: Classes defined within another class (inner classes).

Outside Class in Java:

 Package Declarations: Declaration specifying the package to which the class belongs.
 Import Statements: Statements used to import classes from other packages.
 Interface Definitions: Definitions of interfaces (can be outside classes).
 Enum Declarations: Enumerated types specifying a set of constants (can be outside classes).
 Helper Functions/Utility Methods: Functions or methods not tied to a specific class, often defined in
separate utility classes or files.
 Other Class Definitions: Definitions of separate classes that are not part of the current class hierarchy.

Example:
public class Main {

private String name = "Abdul";


private String email = "[email protected]";
private int age = 29;

private void displayAge() {


System.out.println("My age is " + age);
}

private void displayAgeAfterChange() {


age = 1;
System.out.println("My age is " + age);
}

public static void main(String[] args) {


Main m = new Main();
m.displayAge();
m.displayAgeAfterChange();
}
}

Constructor definition:

Constructor in Java is a special type of method used to initialize objects. It is invoked automatically when an object is
created.

Rules for creating a Constructor:

1) Constructor name should be the same as the class name.


2) Constructors do not have a return type.
Types of constructors:

1) Default Constructor: It is called when we create an object without specifying any arguments. This constructor is
automatically created by Java if no other constructor is defined explicitly.

2) No-Argument Constructor: Similar to the default constructor, it initializes the object when no arguments are
provided. This constructor might perform certain default actions.

3) Parameterized Constructor: A constructor that takes arguments during object creation is called a parameterized
constructor. It allows the initialization of an object with specific values passed as arguments.

Example:
class Employee {
int emp_id;

// Non-argument Constructor
Employee() {
// Body can be empty or you can put any logic here
System.out.println("Employee without id created");
}

// Argument Constructor
Employee(int id) {
emp_id = id;
System.out.println("My Employee id is " + emp_id);
}

// Argument Constructor
Employee(int id, String name) {
System.out.println("My Employee id: " + id);
System.out.println("My Employee name is " + name);
}
}

Example:

class Main {
public static void main(String[] args) {

Employee emp1 = new Employee(); // Constructor called


Employee emp2 = new Employee(3); // Constructor called with an integer argument
Employee emp3 = new Employee(23, "Ahsan"); // Constructor called with an integer and a string
argument
}
}

Type Casting
Type casting refers to the process of converting a value from one data type to another in Java.

Two Types of Casting:

1. Widening Casting (Automatically): Widening Casting (Automatically) refers to the implicit conversion of a
smaller data type to a larger data type size without the need for explicit type conversion in Java.
Example:
int smallNumber = 10;
long largerNumber = smallNumber; // Widening casting (int to long)

2. Narrowing Casting (Manually): Narrowing Casting (Manually) is the explicit conversion of a larger data
type into a smaller data type in Java, potentially leading to data loss or truncation.

For example:
double largeDecimal = 123.456;
int smallNumber = (int) largeDecimal; // Narrowing casting (double to int)

3. Widening Casting: Implicit conversion of a smaller data type into a larger data type size without data loss.

Example:
int smallNumber = 10;
long largerNumber = smallNumber; // Widening casting (int to long)
Static and Non-static (variable and methods)
Static:
Static is used for memory management and it men with static keyword. It belong to the class instead of an
instance of class (object).
Only one instance will be created throughout the project.
We need when we don’t want to change it frequently and it can be used in all over the applications.

Static can be used.


1. Variables (class variable)
2. Method
3. Block
4. Nested class
Static Variables:
Any variable which declare static in data fields in static variable.
Static method:
Any method which is declared with static in method in static model.
Non-static variable/method:
When we joint put keyboard static it is Non-static variable/method.

Example:
public class User {
// Static Variables
public static String bankName = "HBL"; // Corrected variable name to follow conventions
public static int userAccount; // Corrected variable name to follow conventions

// Non-Static Variables
public int userBalance = 0; // Corrected variable name to follow conventions
public String userName;

// Non-Static method to set the username


public void setUserName(String name) {
userName = name; // Set the username
}

// Non-Static method to get the user balance


public int getUserBalance() {
return userBalance;
}

// Non-Static method to display user output


public void displayOutput() {
System.out.println(userName + " has balance " + userBalance);
}

// Static method to get the user account


public static int getUserAccount() {
return userAccount;
}

// Static method to display the user account


public static void displayUserAccount() {
System.out.println("Current Account: " + userAccount);
}

// Main method to demonstrate the functionality


public static void main(String[] args) {
User u = new User(); // Object creation

u.setUserName("Haseed"); // Set the username


u.displayOutput(); // Display user output

u.userBalance = 25000; // Set user balance


u.displayOutput(); // Display updated user output

// Calling static method and setting static variable using class name
User.userAccount = 2; // Set user account using class name

System.out.println(User.getUserAccount()); // Calling static method using class name


}
}

Passing object as an argument


Utilizing objects as parameters in method calls to perform specific tasks within a class.

public class Time {


private int hours, min, sec;

// Constructor without arguments


public Time() {
hours = 0;
min = 0;
sec = 0;
System.out.println("Initial time: " + hours + ":" + min + ":" + sec);
}

// Constructor with arguments


public Time(int h, int m, int s) {
hours = h;
min = m;
sec = s;
}

public void displayTime() {


System.out.println("Time: " + hours + ":" + min + ":" + sec);
}

// Method to add time


public void addTime(Time t1, Time t2) {
sec += t1.sec + t2.sec;
if (sec >= 60) {
sec -= 60;
min++;
}

min += t1.min + t2.min;


if (min >= 60) {
min -= 60;
hours++;
}

hours += t1.hours + t2.hours;


System.out.println("Time is " + hours + " hours " + min + " minutes " + sec + " seconds");
}

public static void main(String[] args)


{Time t1 = new Time(1, 30, 45);
Time t2 = new Time(0, 45, 20);

Time result = new


Time();
result.addTime(t1, t2);
}
}

Example Code Snippets: Demonstrative snippets showcasing class and object creation, error types,
comments,primitive data types, methods, and constructors in Java.

// Parent class
class Humanbeing {
public String name;
protected int age;

public Humanbeing(String name, int age) {


this.name = name;
this.age = age;
}

public void walk() {


System.out.println("walk");
}
}

// Child class
class Man extends Humanbeing {
public String gender;

public Man(String name, int age, String gender) {


super(name, age); // Calling the superclass constructor
this.gender = gender;
}

public void display() {


System.out.println("My name is " + name);
System.out.println("My age is " + age);
System.out.println("My gender is " + gender);
}
}

// Main class
class Main {
public static void main(String[] args) {
Man manObj = new Man("John", 30, "Male"); // Creating a Man object

// Modifying the 'name' attribute of manObj


manObj.name = "Abdul Haseeb"; // Corrected syntax to modify the 'name'

manObj.age = 19;
manObj.gender = "Male";
manobj.display();
}
}

Inheritance
 Inheritance is one of the four pillars of object-oriented programming because it allows the creation of
hierarchical classifications.
 Using inheritance, a general class can be created that defines traits common to a set of related items. This class
can then be inherited by other, more specific classes, each adding those things that are unique to it.
 In the terminology of Java;
o A class that is inherited is called a superclass.
o The class that does the inheriting is called a subclass.
 Therefore, a subclass is a specialized version of a superclass. It inherits all of the variables and methods
defined by the superclass and adds its own, unique elements.

Type of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance*(Not supported in Java)
5. Hybrid/Combination Inheritance
Encapsulation:
The process of binding data and corresponding methods (behavior) together into a single unit is Called
encapsulation.
To achieve encapsulation:
1. Declare class variables/attributes as private: This restricts direct access to these variables from outside the
class.
2. Provide public getter and setter methods:
 Getter methods: These methods retrieve or provide access to the private variables.
 Setter methods: These methods modify or update the value of the private variables.

Example:
class Customer {
private long accNo;
private String name;
private float balanceAmount;

// Setter method for account number


public void setAccNo(long accNo) {
this.accNo = accNo;
}

// Getter method for account number


public long getAccNo() {
return accNo;
}

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for name


public String getName() {
return name;
}

// Setter method for balance amount


public void setBalanceAmount(float balanceAmount) {
this.balanceAmount = balanceAmount;
}

// Getter method for balance amount


public float getBalanceAmount() {
return balanceAmount;
}
}

public class Main {


public static void main(String[] args) {
Customer cust = new Customer();

cust.setName("Abdul Haseeb");
cust.setAccNo(12345678);
cust.setBalanceAmount(250000.6f);

// Displaying customer details


System.out.println("Name: " + cust.getName());
System.out.println("Account Number: " + cust.getAccNo());
System.out.println("Balance Amount: " + cust.getBalanceAmount());
}
}
UMC Diagram
 UMC stands for (United modeling language).it is used to represent you coding/app in structured diagram.

UMC consist of
1. Class name
2. Attribute
3. Method name

UMC Diagram:

Customer
NCC NO: Long

Name: String
balAmount: float
set Accno(long)
get Accnp( )
set name(string)
get name( )

You might also like