Object Oriented Programming (2nd Year 1st Sem) PDF

Document Details

PleasingBohrium

Uploaded by PleasingBohrium

FEU Institute of Technology

Tags

Java programming Object-oriented programming Computer Science Software development

Summary

This document is an introduction to Java programming, focusing on its history, features, and development process. It discusses creating Java applications, exploring the Java Application Architecture, and introduces development tools like NetBeans.

Full Transcript

Module 1: Introduction to Java Technology History of Java Technology Java Features Originally, Java was initially called Oak Simple, Object-Oriented, and Familiar: Java is easy to Developed by James Gosling at Sun Microsystems...

Module 1: Introduction to Java Technology History of Java Technology Java Features Originally, Java was initially called Oak Simple, Object-Oriented, and Familiar: Java is easy to Developed by James Gosling at Sun Microsystems learn and understand. in 1995 (now under Oracle Corporation). Robust and Secure: Designed with security in mind to Java derived its syntax from C and C++, but its minimize errors. object model is simpler and has fewer low-level Architecture-Neutral and Portable: Java bytecode can features. run on any platform with a JVM. Initially designed to control electronic devices in High Performance: Though interpreted, it achieves high Sun's project, Java became a language for web performance using Just-In-Time (JIT) compilation. development, leading to the creation of: The HotJava Interpreted, Threaded, and Dynamic: Java is a browser. multithreaded, dynamic language capable of adapting to Netscape Navigator was developed later to support an evolving environment. Java. Java Editions Steps in Creating a Java Application J2SE (Java 2 Standard Edition): Basic edition for 1. Create Source Code: Write the Java code (e.g., desktop applications. HelloJava.java) using any text editor. J2EE (Java 2 Enterprise Edition): Designed for large- 2. Compile Source Code: Use the javac command to scale enterprise solutions. compile the source into bytecode (e.g., javac J2ME (Java 2 Micro Edition): Optimized for mobile HelloJava.java). devices and embedded systems. 3. Run Program: Execute the compiled code with the JVM and J2SDK java command (e.g., java HelloJava). Java Virtual Machine (JVM): The core of Java’s portability. Java source code is compiled into bytecode (.class files) that can be executed on any Understanding the Java Application Architecture platform through the JVM. Java's portability is due to its architecture that J2SDK (Java Software Development Kit): Includes involves: tools for developing Java applications like: Source Code (.java): Written by the developer. java: The application loader. Bytecode (.class): Generated by compiling the javac: Java compiler. source code using the javac tool. javadoc: Documentation generator. Machine Code: Generated by the JVM from the bytecode, specific to the platform (Windows, Linux, etc.). NetBeans ex. Java Program Integrated Development Environment (IDE): A software tool class HelloWorld { for simplifying the development process. Popular IDEs include public static void main(String args[]) { NetBeans, Eclipse, and Microsoft Visual Studio. System.out.println("Hello World"); Features of NetBeans: } Source Code Editor: With syntax highlighting, code } completion, and error checking. GUI Builder (Matisse): A drag-and-drop tool to design Compilation Command: javac user interfaces without needing to understand layout HelloWorld.java Execution Command: java HelloWorld managers. Refactoring Tools: Renaming, moving, and restructuring code with minimal effort. A Java program begins with a class Debugger: Advanced debugging capabilities with declaration followed by the main method breakpoints, variable watches, and a "fix and continue" where execution starts. feature. Exploring NetBeans IDE: Version Control: Built-in support for CVS and other version control systems. JVM Functionality Advantages of Using NetBeans: User-Friendly: Provides an intuitive interface, easing the Platform Independence: Java's "Write Once, Run development of applications, including JavaBeans, EJB Anywhere" philosophy is based on the JVM's ability (Enterprise Java Beans), and Web Services. to interpret bytecode for different operating Cross-Platform: Since it’s written in Java, it runs on any systems (Windows, Linux, MacOS). OS supporting Java. Productivity Tools: Includes tools like JUnit for testing, profiling tools for performance, and internationalization support for global applications. Setting Up Projects in NetBeans a. Create a New Project: File > New Project > Java Application. b. Add Code: Add functionality to the generated Main class. c. Run the Program: Choose Run > Run Project or press F6 to compile and execute. NetBeans simplifies the process of building and managing Java applications through integrated tools like version control, refactoring, and GUI design utilities, which are crucial for modern software development. -made by ina Module 2: Fundamentals of Java Language Java Terms Java Language Fundamentals class HelloWorld: Defines a class named HelloWorld. Identifiers: Names given to variables, methods, classes, public: Access modifier, allowing access to the etc. method from other classes. Rules: static: Denotes that the method belongs to the class Must begin with a letter, underscore, or and can be called without creating an instance of the currency symbol. class. Must not use reserved Java keywords. void: Specifies that the method does not return any Keywords: Reserved words in Java that cannot be used value. as identifiers. System.out.println("Hello World"): Prints output to Examples: int, class, if, static, return, void. the console. Comments: Single-line comment: // Comment here Java Data Types Multi-line comment: Primitive Data Types: Documentation comment: byte: 1 byte, values between -128 and 127. short: 2 bytes, values between -32,768 and ex. Variables (Syntax) 32,767. int: 4 bytes, values between -2,147,483,648 ; and 2,147,483,647. long: 8 bytes, values from Long.MIN_VALUE to ex. Variables Decleration Long.MAX_VALUE. String name; float: 4 bytes, values from Float.MIN_VALUE int age; to Float.MAX_VALUE. double price = 55.66; double: 8 bytes, values from Double.MIN_VALUE to Double.MAX_VALUE. ex. Assigning a value (Syntax) boolean: 1 bit, values true or false. char: 2 bytes, values from \u0000 to \uFFFF. = value; Derived Data Types: Examples: String, Date, Integer, Double, Float. ex. Assigning a value name = "Maria Blanco"; age = 22; Wrapper Classes price = 200.50; Used to convert primitive data types into objects. Examples: Integer for int Float for float ex. Basic Input and Output Double for double class Output { Long for long public static void main(String[] args) { System.out.println("1. println"); Basic Input and Output System.out.print("2. print "); System.out.print("3. print"); Output Methods: } System.out.println(): Prints the output and } moves the cursor to the next line. System.out.print(): Prints the output without OUTPUT: moving the cursor to the next line. System.out.printf(): Provides formatted 1. println output (similar to printf in C/C++). 2. print 3. print Input Using Scanner ex. Basic Input and Output The Scanner class is used for reading user input import java.util.Scanner; and is part of the java.util package. public class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username: "); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } } OUTPUT: Enter username: MyUsername Username is: MyUserName -made by ina Module 3: Operators in Java Unary Arithmetic Operators ex. Increment and Decrement Used for simple arithmetic with one operand. int a = 5; System.out.println(++a); Operators: // Outputs: 6 (Prefix) + (positive sign) - (negative sign) System.out.println(a++); ++ (increment) // Outputs: 6 (Postfix, value is updated after) -- (decrement) Increment and Decrement Formats: Prefix: Operator before the variable (++a, -- a) – modifies the value before usage. Postfix: Operator after the variable (a++, a--) – modifies the value after usage. Binary Arithmetic Operators ex. Binary Arithmetic Operators Performs basic arithmetic operations between two int result = 10 + 5 * 2; operands. // result is 20 due to precedence Operators: + (addition) - (subtraction) * (multiplication) / (division) % (modulus – remainder of division) Precedence Levels: ex. Bitwise Operators *, /, % have higher precedence than +, -. (PEMDAS) int a = 5; // 0101 in binary int b = 3; // 0011 in binary Bitwise Operators Used to manipulate individual bits of integer values. System.out.println(a | b); Logic Tables: // Outputs: 7 (0111 in binary) OR (|): Returns 1 if either operand has a bit set to 1. System.out.println(a & b); AND (&): Returns 1 only if both operands have bits // Outputs: 1 (0001 in binary) set to 1. XOR (^): Returns 1 if one operand has a bit set to 1 but not both. NOT (~): Inverts all bits. ex. Shift Operators int a = 8; // 1000 in binary Shift Operators System.out.println(a >> 2); // Outputs: 2 (0010 in binary) Shifts bits of a number left or right. Operators: System.out.println(a >: Right shift (preserves the sign). // Outputs: 32 (100000 in binary) >: Unsigned right shift (does not preserve sign). ex. Relational Operators Relational Operators int x = 10, y = 20; Compare two values and return a boolean result. Operators: System.out.println(x > y); // Outputs: false System.out.println(x != y); // Outputs: true > (greater than) >= (greater than or equal to) < (less than) ex. Logical Operators b) ? a : b; // max will be 20 -made by ina Module 4: Java Control Structures and Arrays Control Structures ex. If-Else (Syntax) Control structures allow a program to make decisions and repeat if (condition) { tasks based on conditions. // code to execute if condition is true if-else Statement } else { Executes a block of code if a condition is true; otherwise, it // code to execute if condition is false executes a different block. } switch Statement Allows multi-way branching based on the value of an integer or enum. while Loop ex. Switch (Syntax) Repeats a block of code as long as the condition is true.. switch (variable) { do-while Loop case constant1: Ensures the block of code executes at least once before // code for constant1break; checking the condition. case constant2: for Loop // code for constant2break; Iterates a block of code a fixed number of times, based on default: a condition. // default codebreak; for-each Loop } Iterates through elements in a collection or array. break and continue Statements break: Exits the loop or switch statement immediately. ex. While Loop (Syntax) continue: Skips the rest of the loop body and continues to the next iteration. while (condition) { Arrays // code to execute An array is a collection of elements of the same type, stored at } contiguous memory locations. ex. Do-While Loop (Syntax) do { // code to execute } while (condition); ex. For Loop (Syntax) for (initialization; condition; update) { // code to execute } ex. For-Each Loop (Syntax) for (type element : collection) { // code to execute } ex. Break/Continue (Syntax) break; continue; ex. Array Declaration (Syntax) type[] arrayName = new type[length]; ex. Array Initialization (Syntax) type[] arrayName = {value1, value2,...}; ex. Accessing Elements (Syntax) arrayName[index] = value; ex. Multi-dimensional Array: (Syntax) type[][] arrayName = new type[rows][columns]; -made by ina Module 5: Introduction to Object Oriented Programming Abstraction ex. Abstraction Abstraction is the process of hiding complex implementation details // Abstract class with abstract method and showing only the essential features of an object. abstract class Animal { Encapsulation abstract void sound(); // Abstract method (no implementation) Encapsulation involves bundling data (attributes) and methods that } manipulate the data within a single unit (class), and restricting access to some of the object’s components. // Subclass (Dog) that provides implementation Inheritance class Dog extends Animal { Inheritance allows a new class to inherit fields and methods from void sound() { an existing class, promoting code reusability. System.out.println("Barks"); } Polymorphism } Polymorphism allows one interface to be used for different data types or classes, meaning methods can have different behaviors public class Main { public static void main(String[] args) { depending on the object. Animal dog = new Dog(); // Upcasting, referencing Dog with Animal Association dog.sound(); // Output: Barks Association represents a relationship between objects. One object } can have a reference to another object. } “this" Keyword The this keyword refers to the current object instance. It's useful ex. Encapsulation to distinguish between instance variables and parameters with the class Student { same name. // Private fields private String name; Access Modifiers private int age; Access modifiers determine the visibility of class members (fields // Setter method for name (mutator) and methods). public void setName(String name) { public: Accessible from any class. this.name = name; private: Accessible only within the same class. } protected: Accessible within the same package and by subclasses. // Getter method for name (accessor) (no modifier): Default access, package-private (accessible only public String getName() { within the same package). return this.name; } ex. Polymorphism ex. Association // Setter method for age class Animal { class Engine { public void setAge(int age) { public void sound() { String type; if (age > 0) { System.out.println("Animal makes a Engine(String type) { this.age = age; sound"); } this.type = type; } } } } } class Dog extends Animal { public void sound() { class Car { // Getter method for age String model; System.out.println("Dog barks"); Engine engine; public int getAge() { } } // Car "has-a" Engine return this.age; } Car(String model, Engine engine) { class Cat extends Animal { this.model = model; } public void sound() { System.out.println("Cat meows"); this.engine = engine; } } public class Main { } public void showDetails() { public static void main(String[] args) { public class Main { System.out.println("Model: " + model + ", Student student = new Student(); public static void main(String[] args) { Engine: " + engine.type); student.setName("John"); } Animal myAnimal = new Animal(); Animal myDog = new Dog(); } student.setAge(20); Animal myCat = new Cat(); System.out.println("Name: " + public class Main { public static void main(String[] args) { student.getName()); myAnimal.sound(); // Output: Animal makes System.out.println("Age: " + a sound Engine v8 = new Engine("V8"); myDog.sound(); // Output: Dog barks v8); Car mustang = new Car("Ford Mustang", student.getAge()); myCat.sound(); // Output: Cat meows mustang.showDetails(); } } } // Output: Model: Ford Mustang, Engine: V8 } } } ex. “this" Keyword ex. Inheritance class Employee { ex. Access Modifiers String name; // Superclass (Parent) class Person { public String name; class Vehicle { // Constructor with the same name for String brand = "Ford"; parameter and field // Public - accessible from everywhere public Employee(String name) { private int age; // Private - accessible only in this class this.name = name; public void honk() { // 'this' distinguishes the instance variable from the parameter public void setAge(int age) { System.out.println("Beep beep!"); } this.age = age; // Accessing private field within the class } } } public void showName() { System.out.println("Employee Name: " + this.name); public int getAge() { // Subclass (Child) } return this.age; } // Accessing private field within the class class Car extends Vehicle { } String modelName = "Mustang"; } public class Main { } public static void main(String[] args) { Employee emp = new Employee("Alice"); public class Main { emp.showName(); public static void main(String[] args) { Person person = new Person(); public class Main { // Output: Employee Name: Alice person.name = "Bob"; // Public, can be public static void main(String[] args) { } } accessed directly Car myCar = new Car(); person.setAge(25); // Access through System.out.println(myCar.brand + public method " " + myCar.modelName); // Output: Ford System.out.println(person.name + " is " + Mustang person.getAge() + " years old."); } myCar.honk(); // Output: Beep } beep! } } -made by ina Module 6: Encapsulation and Inheritance Encapsulation ex. Encapsulation Encapsulation ensures that sensitive data is hidden from users by public class Person { restricting access to certain class variables or methods. This is // private = restricted access private String name; achieved by: Declaring class variables/attributes as private. // Getter method Providing public getter (accessor) and setter (mutator) methods to public String getName() { return name; access and update the value of private variables. } Why Encapsulation? // Setter method Control: The class controls how its data is accessed or public void setName(String newName) { modified. } this.name = newName; Security: Sensitive data can be hidden and protected from } unauthorized access. public class Main { Read-only or Write-only fields: You can create read-only public static void main(String[] args) { fields (by omitting the setter) or write-only fields (by Person myObj = new Person(); myObj.setName("John"); omitting the getter). // Set the value of the name variable Flexibility: Changes made in one part of the code (e.g., internal System.out.println(myObj.getName()); // Output: John implementation) do not affect other parts. } } Inheritance In this example, name is a private variable, so it cannot be Inheritance allows a class (called a subclass) to inherit fields and accessed directly outside the class. Instead, the getName() methods from another class (called a superclass). The subclass can and setName() methods are used to access and modify the value. also override methods and add its own behavior. Superclass: Person is the superclass with a constructor and a method getName(). ex. Inheritance Subclass: Student is the subclass that extends Person and // Superclass overrides the getName() method to add its own behavior. public class Person { super(name) calls the constructor of the superclass Person. protected String name; Types of Inheritance public Person(String name) { Single inheritance: A class inherits from one superclass. this.name = name; Multi-level inheritance: A class inherits from another subclass, } forming a chain. public String getName() { return name; } The this and super Keywords } this: Refers to the current object in a method or constructor. // Subclass super: Refers to the superclass of the current object and can be public class Student extends Person { public Student(String name) { used to call superclass methods or constructors. super(name); // Call superclass constructor } Method Overriding // Overriding the getName method @Override A subclass can override a method from its superclass, providing its public String getName() { return "Student: " + super.getName(); own implementation. } } Final Methods and Final Classes public class Main { A final class cannot be subclassed. public static void main(String[] args) { A final method cannot be overridden by subclasses. Student student = new Student("Anna"); System.out.println(student.getName()); // Output: Student: Anna } } ex. this and super ex. Method Overriding class Person { protected String name; class Person { public String getName() { ex. Multi-Level Inheritance return "Parent: getName"; public Person(String name) { } // Superclass this.name = name; } class Animal { } public void eat() { } class Student extends Person { System.out.println("This animal eats food."); @Override } class Student extends Person { public String getName() { } public Student(String name) { return "Student: getName"; super(name); // Call the superclass } // Subclass constructor } class Dog extends Animal { } public void bark() { public class Main { System.out.println("The dog barks."); public void display() { public static void main(String[] args) { } System.out.println("Name: " + this.name); Student student = new Student(); } // 'this' refers to current object's name System.out.println(student.getName()); } // Output: Student: getName // Sub-subclass } } class Puppy extends Dog { } public void weep() { public class Main { System.out.println("The puppy weeps."); public static void main(String[] args) { } Student s = new Student("John"); } s.display(); // Output: Name: John } public class Main { } public static void main(String[] args) { Puppy puppy = new Puppy(); puppy.eat(); // Inherited from Animal ex. Final Methods and Final Classes puppy.bark(); // Inherited from Dog puppy.weep(); // From Puppy class } // Final class } public final class Person { public final String getName() { return "This is a final method."; } } // This will cause an error as final classes cannot be extended. // class Student extends Person { } // Final methods cannot be overridden, so trying to do so would also result in an error. -made by ina

Use Quizgecko on...
Browser
Browser