AGENDA Classes: Class fundamentals;Methods; Naming conventions; Declaring objects; Access specifiers; Constructors; Command line arguments; Method Overloading; keywords: this, final; Static; abstract, finalize. Inheritance: Single; Multilevel inheritance; Method overriding-Dynamic method dispatch; Abstract classes, Usage of super. Interfaces: Defining an interface; Implementing interfaces; Extending interfaces. Packages: user defined packages; creating and implementing packages. 2
3.
OBJECT-ORIENTED PROGRAMMING (OOP) • Object-OrientedProgramming (OOP) is a programming paradigm based on the concept of "objects", which are instances of classes. Java is a pure object-oriented language Key Features of OOPs in Java: • Structures code into logical units (classes and objects) • Keeps related data and methods together (encapsulation) • Makes code modular, reusable and scalable 3
4.
CLASS AND OBJECTIN JAVA 4 1. Class A Class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Using classes, you can create multiple objects with the same behavior instead of writing their code multiple times. In general, class declarations can include these components in order: Modifiers: A class can be public or have default access. Class name: The class name should begin with the initial letter capitalized by convention. Body: The class body is surrounded by braces, { }.
5.
5 EXAMPLE public class Car { Stringcolor; // State (fields) int year; void drive() // Behavior (method) { System.out.println("The car is driving."); } }
6.
OBJECT 6 An objectis an instance of a class. It represents a real-world entity that has: State represented by fields/variables → Behavior represented by methods → When a class is the blueprint, an object is the real thing built from that blueprint. Example: public class Main { public static void main(String[] args) { Car myCar = new Car(); // Creating an object of Car myCar.color = "Red"; // Setting state myCar.year = 2022; System.out.println(myCar.color); // Accessing state myCar.drive(); // Calling behavior } }
7.
7 Car myCar =new Car(); • Car class name → • myCar object name (reference variable) → • new keyword to create a new object → • Car() constructor that initializes the object →
9 WHAT ARE VARIABLESIN JAVA? • Variables are containers that store data values during program execution. They hold information that can be used and manipulated by the program. Example: int age; // Declaration age = 25; // Initialization // or combined int score = 100; // Declaration + Initialization
10.
TYPES OF VARIABLESIN JAVA Variable Type Where Declared Lifetime Example Local Variables Inside methods Exists only during method execution int count = 0; Instance Variables Inside class but outside methods Exists as long as object exists String name; Static Variables (Class Variables) Inside class with static keyword Exists as long as the program runs static int totalStudents; 10
11.
METHODS IN JAVA JavaMethods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects. 11
13 EXAMPLE // Creating amethod public class Geeks { public void printMessage() { System.out.println("Hello, Geeks!"); } public static void main(String[] args) { // Create an instance of the Method class Geeks obj = new Geeks(); // Calling the method obj.printMessage(); } } Output Hello, Geeks!
14.
14 TYPES OF METHODSIN JAVA 1. Predefined Method • Predefined methods are the method that is already defined in the Java class libraries. It is also known as the standard library method or built-in method. For example, random() method which is present in the Math class and we can call it using the ClassName.methodName() as shown in the below example. Example • Math.random() // returns random value • Math.PI // return pi value
15.
15 2. 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. Example: // user define method Greet() setName()
16.
16 DIFFERENT WAYS TOCREATE JAVA METHOD 1. Instance Method: Access the instance data using the object name. Declared inside a class. Example: // Instance Method void method_name() { // instance method body } 2. Static Method: Access the static data using class name. Declared inside class with static keyword. Example: // Static Method static void method_name() { // static method body }
17.
17 DIFFERENCE BETWEEN PROCEDURE-ORIENTEDPROGRAMMING AND OBJECT-ORIENTED PROGRAMMING Aspect Procedure-Oriented Programming (POP) Object-Oriented Programming (OOP) Basic Concept Focuses on functions or procedures that operate on data. Focuses on objects that combine data and behavior. Approach Top-down approach Bottom-up approach Data and Functions Data and functions are separate Data and methods are bundled together in objects Modularity Divides program into functions Divides program into classes/objects Data Access Data is exposed and can be accessed freely Data is hidden (encapsulated) and accessed via methods Reusability Less emphasis on reuse High emphasis on reusability via inheritance and polymorphism
18.
18 Examples of LanguagesC, Pascal Java, C++, Python (supports OOP) Inheritance Support No inheritance Supports inheritance Polymorphism Support Not supported Supported Abstraction Support Limited abstraction Supports abstraction Execution Flow Follows a sequential flow of functions Interaction between objects triggers flow
19.
19 CONSTRUCTORS • A specialtype of method used to initialize new objects of a class. They have the same name as the class and do not have a return type. If no constructor is explicitly defined, Java provides a default no-argument constructor. Characteristics of Constructors: • Same Name as the Class • No Return Type • Automatically Called on Object Creation • Used to Set Initial Values for Object Attributes
20.
20 THEN WHY DOWE USE CONSTRUCTORS AT ALL? • Constructors are not about forcing input, they are about ensuring proper initialization. Let me explain: Without constructor • You create an object it’s “empty” at first. → • If you forget to assign values, you may end up with incomplete data (null or 0). With constructor • The object is always initialized properly at creation. • No chance of forgetting to set values. • Cleaner and more reliable code.
21.
21 TYPES OF CONSTRUCTORSIN JAVA • Default Constructor (no parameters) gives default values. → • Parameterized Constructor (with parameters) allows passing values at the time of object creation. → • Copy Constructor (optional, user-defined) copies values from another object. → Example for Constructor: class Dog { String name; int age; Dog(String n, int a) { // Constructor name = n; age = a; } // ... methods }
24 CREATE AN OBJECT •In Java, an object is created from a class. We have already created the class named Main, so now we can use this to create objects. Example:
26 NAMING CONVENTIONS • Javanaming 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.
27.
27 NAMING CONVENTIONS In Java,the following are the naming conventions for different types of entities: • Package names: all lowercase letters, no spaces, multiple words separated by dots (e.g. java.util) • Class names: start with a capital letter, followed by camelCase (e.g. String, ArrayList) • Interface names: start with a capital letter, followed by camelCase (e.g. Runnable, Comparable) • Method names: start with a lowercase letter, followed by camelCase (e.g. println(), toString()) • Constant names: all uppercase letters, multiple words separated by underscores (e.g. PI, MAX_VALUE) • Variable names: start with a lowercase letter, followed by camelCase (e.g. name, counter
28.
28 ACCESS MODIFIERS INJAVA • In Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program
29.
29 1. Default AccessModifier • When no access modifier is specified for a class, method, or data member, it is said to have the default access modifier by default. This means only classes within the same package can access it. 2. Private Access Modifier • The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of the same package will not be able to access these members. Top-level classes or interfaces cannot be declared as private because, private means "only visible within the enclosing class". Protected means "only visible within the enclosing class and any subclasses".
32 3. Protected AccessModifier • The protected access modifier is specified using the keyword protected. The methods or data members declared as protected are accessible within the same package or subclasses in different packages. • Example:
33.
33 4. Public AccessModifier • The public access modifier is specified using the keyword public. • The public access modifier has the widest scope among all other access modifiers. • Classes, methods, or data members that are declared as public are accessible from everywhere in the program. There is no restriction on the scope of public data members.
35 METHOD OVERLOADING • inJava is a feature that allows a class to have multiple methods with the same name, provided their parameter lists are different. This is a form of compile-time polymorphism, where the compiler determines which method to execute based on the method signature (name and parameter list) at compile time. • Example:
38 JAVA COMMAND-LINE ARGUMENT •Java command-line argument is an argument, i.e., passed at the time of running the Java program. Command- line arguments passed from the console can be received by the Java program and used as input. Example: java Geeks Hello World • Note: Here, the words Hello and World are the command-line arguments. JVM will collect these words and will pass these arguments to the main method as an array of strings called args. The JVM passes these arguments to the program inside args[0] and args[1]. Example: In this example, we are going to print a simple argument in the command line. // Java Program to Illustrate First Argument class GFG{ public static void main(String[] args) { // Printing the first argument System.out.println(args[0]); } }
42 FINAL KEYWORD • Whena variable is declared with the final keyword, its value can't be changed, essentially, a constant. This also means that you must initialize a final variable. • the keyword "final" is used to declare a constant value or to indicate that a particular aspect of a class, method or variable cannot be overridden or modified
45 INHERITANCE Java Inheritance isa fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class. Types of Inheritance 1. Java supports the following four types of inheritance: 2. Single Inheritance 3. Multilevel Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance
46.
46 SINGLE INHERITANCE • Insingle inheritance, a subclass is derived from only one superclass. It inherits the properties and behavior of a single-parent class. Sometimes it is also known as simple inheritance.
47.
47 // example //Super class classVehicle { Vehicle() { System.out.println("This is a Vehicle"); } } // Subclass class Car extends Vehicle { Car() { System.out.println("This Vehicle is Car"); } } public class Test { public static void main(String[] args) { // Creating object of subclass invokes base class constructor Car obj = new Car(); } } output is This is a Vehicle This Vehicle is Car