thirunavukkarasu57
25 views
68 slides
Mar 05, 2025
Slide 1 of 68
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
About This Presentation
OOPS SECOND UNIT
Size: 1.5 MB
Language: en
Added: Mar 05, 2025
Slides: 68 pages
Slide Content
CS3391-OBEJCT ORIENTED PROGRAMMING UNIT - 2 INHERITANCE, PACKAGES AND INTERFACES Overloading Methods – ObJects as Parameters – Returning Objects –Static, Nested and Inner Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces: Packages – Packages and Member Access –Importing Packages – Interfaces. Mr.k.THIRUNAVUKKARASU.,M.E ASsISTANT PROFESSOR DEPArtment of cse tpgit-vellore-02 Unit - II Inheritance, Packages And Interfaces
Introduction Overloading Methods Objects as Parameters Returning Objects Static Nested Classes Inner Classes Inheritance Basics Types of Inheritance CONTENT LIST <#> Unit - II Inheritance, Packages And Interfaces Super Keyword Method Overriding Dynamic Method Dispatch Abstract Classes final Keyword with Inheritance Packages in Java Importing Packages Interfaces in Java
Java is an object-oriented programming language that enables developers to create robust and scalable applications. fundamental Java concepts, including: Method Overloading: Defining multiple methods with the same name but different parameters to perform various tasks. Inheritance: A mechanism that allows a new class (the subclass) to inherit attributes and methods from an existing class (the superclass), promoting code reusability. Abstract Classes and Interfaces: Tools for defining abstract data types that enforce the implementation of specific methods, aiding in the design of flexible and scalable systems. Packages: Used to organize classes and interfaces into namespaces, enhancing code modularity and preventing naming conflicts. INTRODUCTION <#> Unit - II Inheritance, Packages And Interfaces
Method overloading allows a class to have more than one method with the same name but different parameter lists (number or type of parameters). Key Points: Increases code readability and reusability. Method signatures must differ in parameter type or number of parameters. Return type can be the same or different, but it's not considered for overloading. Overloading Methods <#> Unit - II Inheritance, Packages And Interfaces
Program: class Calculator { // Overloaded methods for addition int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } double add(double a, double b) { return a + b; } } public class OverloadingDemo { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(2, 3)); // Outputs: 5 System.out.println(calc.add(2, 3, 4)); // Outputs: 9 System.out.println(calc.add(2.5, 3.5)); // Outputs: 6.0 } } <#> Unit - II Inheritance, Packages And Interfaces An illustration showing three boxes labeled "Method 1", "Method 2", and "Method 3", each with the same method name add(). The difference between the boxes is that Method 1 has two int parameters, Method 2 has three int parameters, and Method 3 has two double parameters. This image will depict how method overloading works in Java, with different methods being invoked depending on the arguments passed.
<#> Unit - II Inheritance, Packages And Interfaces
Example Program 2: class Printer { // Overloaded methods for printing void print(int number) { System.out.println("Printing integer: " + number); } void print(String text) { System.out.println("Printing string: " + text); } void print(double number) { System.out.println("Printing double: " + number); } } public class OverloadingExample { public static void main(String[] args) { Printer printer = new Printer(); printer.print(10); // Prints integer printer.print("Hello!"); // Prints string printer.print(3.14); // Prints double } } <#> Unit - II Inheritance, Packages And Interfaces
Definition: In Java, objects can be passed as parameters to methods. This allows methods to access and modify the state of the objects passed to them. Key Point: Java is "pass-by-value," but when passing objects, the reference to the object is passed by value. How Object Passing Works When an object is passed to a method, a copy of the reference to that object is made. Changes made to the object inside the method affect the original object. Example: Consider a method that modifies an attribute of the object passed to it. Obects as Paameters <#> Unit - II Inheritance, Packages And Interfaces
Example Classes class Student { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println ("Name: " + name + ", Age: " + age); } } <#> Unit - II Inheritance, Packages And Interfaces Method Modifying Object void updateAge (Student student , int newAge ) { student.age = newAge ; // Modifying the age of the student object } Main Class Example public class Main { public static void main(String[] args ) { Student student = new Student("Alice", 20); System.out.println ("Before update:"); student.display (); // Output: Name: Alice, Age: 20 updateAge (student, 21); // Passing object to method System.out.println ("After update:"); student.display (); // Output: Name: Alice, Age: 21 } static void updateAge (Student student , int newAge ) { student.age = newAge ; // Modifying the object } }
In Java, when a method returns an object, it means that the method returns a reference to an object that is created within the method. This allows the caller of the method to use the returned object as needed. ReTURNING OBJECTS <#> Unit - II Inheritance, Packages And Interfaces public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName () { return name; } public int getAge () { return age; } } public class Main { public static Student getStudent () { Student student = new Student("John Doe", 20); return student; } public static void main(String[] args ) { Student student = getStudent (); System.out.println ("Name: " + student.getName ()); System.out.println ("Age: " + student.getAge ()); } }
In this example, the getStudent () method creates a new Student object and returns it. The main() method then calls getStudent () and assigns the returned object to a Student variable. We can then access the name and age properties of the returned object using the getName () and getAge () methods. Example 2: Returning an Array of Objects <#> Unit - II Inheritance, Packages And Interfaces public class Student { // same as before } public class Main { public static Student[] getStudents () { Student[] students = new Student[2]; students[0] = new Student("John Doe", 20); students[1] = new Student("Jane Doe", 21); return students; } public static void main(String[] args ) { Student[] students = getStudents (); for (Student student : students) { System.out.println ("Name: " + student.getName ()); System.out.println ("Age: " + student.getAge ()); } } }
In this example, the getStudents () method creates an array of Student objects and returns it. The main() method then calls getStudents () and assigns the returned array to an array of Student objects. We can then iterate over the array using a for-each loop and access the name and age properties of each returned object using the getName () and getAge () methods. Returning an Object from a Static Method public class Student { // same as before } public class Main { public static Student getStudent () { return new Student("John Doe", 20); } public static void main(String[] args ) { Student student = getStudent (); System.out.println ("Name: " + student.getName ()); System.out.println ("Age: " + student.getAge ()); } } <#> Unit - II Inheritance, Packages And Interfaces
Key Points When a method returns an object, it returns a reference to an object that is created within the method. The caller of the method can use the returned object as needed. Returning an array of objects is similar to returning a single object, but instead of returning a single object, you return an array of objects. Static methods can also return objects, but they do not have access to instance variables or methods. <#> Unit - II Inheritance, Packages And Interfaces
A static class is a class that is nested inside another class, but it is not tied to an instance of the outer class. This means that a static class can be used without creating an instance of the outer class. Example: CopyReplit public class OuterClass { public static class StaticInnerClass { public void printMessage () { System.out.println ("Hello from Static Inner Class!"); } } } To use the static class, you simply need to import the outer class and create an instance of the static class: OuterClass.StaticInnerClass sic = new OuterClass.StaticInnerClass (); sic.printMessage (); // Output: Hello from Static Inner Class! Static Classes <#> Unit - II Inheritance, Packages And Interfaces
A nested class is a class that is defined inside another class. It is not necessarily tied to an instance of the outer class, but it is still associated with the outer class. Example: public class OuterClass { private int x; public class NestedInnerClass { public void printMessage () { System.out.println ("Hello from Nested Inner Class!"); } } } To use the nested class, you need to create an instance of the outer class and then access the nested class: OuterClass outer = new OuterClass (); OuterClass.NestedInnerClass nic = outer.new NestedInnerClass (); nic.printMessage (); // Output: Hello from Nested Inner Class! Nested Classes <#> Unit - II Inheritance, Packages And Interfaces
An inner class is a class that is defined inside another class and is tied to an instance of the outer class. This means that an inner class has access to the members of the outer class, including private variables and methods. Example: public class OuterClass { private int x; public void doSomething () { new InnerClass (this); } private class InnerClass { private OuterClass outer; public InnerClass ( OuterClass outer) { this.outer = outer; } public void printMessage () { System.out.println ("Hello from Inner Class!"); System.out.println ("Accessing outer variable: " + outer.x ); } }} Inner Classes <#> Unit - II Inheritance, Packages And Interfaces
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and behaviors (methods) from another class. In Java, inheritance enables code reuse, establishes a hierarchical relationship between classes, and allows for polymorphism. Types of Inheritance in Java Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance (through interfaces) Hybrid Inheritance (using a combination of the above) Inheritance Basics <#> Unit - II Inheritance, Packages And Interfaces
<#> Unit - II Inheritance, Packages And Interfaces
SINGLE INHERITANCE <#> Unit - II Inheritance, Packages And Interfaces In single inheritance, one class (subclass) inherits from another class
<#> Unit - II Inheritance, Packages And Interfaces class Animal { // Superclass void eat() { System.out.println ("Eating..."); }} class Dog extends Animal { // Subclass void bark() { System.out.println ("Barking..."); }} public class Main { public static void main(String[] args ) { Dog dog = new Dog(); dog.eat (); // Inherited method dog.bark (); // Dog's own method }}
In multilevel inheritance, a class is derived from another class, which is also derived from another class. Multilevel Inheritance <#> Unit - II Inheritance, Packages And Interfaces
<#> Unit - II Inheritance, Packages And Interfaces class Animal { // Superclass void eat() { System.out.println ("Eating..."); }} class Dog extends Animal { // Subclass void bark() { System.out.println ("Barking..."); }} class Puppy extends Dog { // Sub-subclass void weep() { System.out.println ("Weeping..."); }} public class Main { public static void main(String[] args ) { Puppy puppy = new Puppy(); puppy.eat (); // Inherited from Animal puppy.bark (); // Inherited from Dog puppy.weep (); // Puppy’s own method } }
In hierarchical inheritance, multiple subclasses inherit from a single superclass. Hierarchical Inheritance <#> Unit - II Inheritance, Packages And Interfaces class Animal { // Superclass void eat() { System.out.println ("Eating..."); } } class Dog extends Animal { // Subclass 1 void bark() { System.out.println ("Barking..."); } } class Cat extends Animal { // Subclass 2 void meow() { System.out.println ("Meowing..."); } } public class Main { public static void main(String[] args ) { Dog dog = new Dog(); dog.eat (); // Inherited from Animal dog.bark (); // Dog's own method Cat cat = new Cat(); cat.eat (); // Inherited from Animal cat.meow (); // Cat's own method } }
<#> Unit - II Inheritance, Packages And Interfaces
Java does not support multiple inheritance through classes (to avoid ambiguity). However, it can be achieved through interfaces. Multiple Inheritance (via Interfaces) <#> Unit - II Inheritance, Packages And Interfaces
<#> Unit - II Inheritance, Packages And Interfaces interface CanRun { void run(); } interface CanBark { void bark(); } class Dog implements CanRun , CanBark { // Implementing multiple interfaces public void run() { System.out.println ("Dog is running..."); } public void bark() { System.out.println ("Dog is barking..."); } } public class Main { public static void main(String[] args ) { Dog dog = new Dog(); dog.run (); // Dog's own method dog.bark (); // Dog's own method } }
Hybrid inheritance is a combination of two or more types of inheritance. Java does not support hybrid inheritance directly through classes, but it can be achieved through interfaces. Hybrid Inheritance <#> Unit - II Inheritance, Packages And Interfaces
Single Inheritance allows a class to inherit from one superclass. Multilevel Inheritance involves a chain of classes, each inheriting from the previous one. Hierarchical Inheritance allows multiple subclasses to inherit from a single superclass. Multiple Inheritance is achieved through interfaces in Java. Hybrid Inheritance combines multiple types of inheritance, typically using interfaces to bypass Java's restrictions on multiple inheritance with classes. <#> Unit - II Inheritance, Packages And Interfaces
The super keyword in Java is used primarily in two contexts: Accessing superclass methods and variables: It allows you to refer to the immediate parent class's attributes and methods. Calling superclass constructors: It can be used to invoke the constructor of the superclass. Accessing Superclass Methods and VariablesDescription : When you override a method in a subclass and you still want to call the method from the superclass, you can use the super keyword. Super keyword <#> Unit - II Inheritance, Packages And Interfaces
<#> Unit - II Inheritance, Packages And Interfaces class Animal { void sound() { System.out.println ("Animal makes a sound"); } } class Dog extends Animal { void sound() { super.sound (); // Calls the superclass method System.out.println ("Dog barks"); } } public class Main { public static void main(String[] args ) { Dog dog = new Dog(); dog.sound (); } }
Calling Superclass Constructors The super keyword can also be used to call a constructor of the superclass from a subclass. This must be the first statement in the subclass constructor. <#> Unit - II Inheritance, Packages And Interfaces class Vehicle { Vehicle() { System.out.println ("Vehicle created"); }} class Car extends Vehicle { Car() { super(); // Calls the Vehicle constructor System.out.println ("Car created"); }} public class Main { public static void main(String[] args ) { Car car = new Car(); }}
Use super.methodName () to call a method of the superclass. Use super() to invoke the constructor of the superclass. The super keyword can only be used within the body of the subclass. When using super to call a constructor, it must be the first statement in the constructor of the subclass. If no constructor is explicitly defined in a subclass, Java automatically calls the no-argument constructor of the superclass. <#> Unit - II Inheritance, Packages And Interfaces
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows a subclass to offer a more specific behavior than the superclass. Key Points : Same Method Name : The method in the subclass must have the same name, return type, and parameters as the method in the superclass. Inheritance : Method overriding is only possible through inheritance (the subclass inherits from the superclass). Dynamic Method Dispatch : Method overriding is an example of dynamic method dispatch, which means that the method that gets executed is determined at runtime based on the object's actual type, not the type of the reference variable. Method Overriding <#> Unit - II Inheritance, Packages And Interfaces
Example of Method Overriding Let's take a detailed look at a Java example demonstrating method overriding. Step 1: Define a Superclass class Animal { void sound() { System.out.println ("Animal makes a sound"); }} <#> Unit - II Inheritance, Packages And Interfaces Define a Subclass 1 class Dog extends Animal { @Override void sound() { System.out.println ("Dog barks"); } } Define a Subclass 2 class Cat extends Animal { @Override void sound() { System.out.println ("Cat meows"); } }
public class Main { public static void main(String[] args ) { Animal myAnimal = new Animal(); // Animal reference and object Animal myDog = new Dog(); // Animal reference but Dog object Animal myCat = new Cat(); // Animal reference but Cat object myAnimal.sound (); // Outputs: Animal makes a sound myDog.sound (); // Outputs: Dog barks myCat.sound (); // Outputs: Cat meows }} <#> Unit - II Inheritance, Packages And Interfaces
Superclass and Subclass: We define a superclass Animal and two subclasses Dog and Cat that override the sound() method. Dynamic Method Dispatch:When we call myDog.sound (), the Java runtime determines that myDog is actually a Dog object, so it invokes the overridden sound() method in the Dog class.Similarly , myCat.sound () invokes the sound() method in the Cat class.Polymorphism : The ability to use a superclass reference to refer to subclass objects is a feature of polymorphism in Java. <#> Unit - II Inheritance, Packages And Interfaces Runtime Polymorphism: It enables runtime polymorphism, allowing a method to behave differently based on the object that it is invoked on.Code Reusability: It promotes the reuse of code, as you can extend the behavior of existing classes without modifying their code. Flexibility and Maintenance: It makes it easier to modify and maintain code, as you can change the behavior of derived classes without impacting the base class.
Dynamic Method Dispatch is a mechanism by which a call to an overridden method is resolved at runtime rather than compile time. It is a key feature of polymorphism in Java, allowing for the implementation of late binding. How Dynamic Method Dispatch Works Superclass Reference : A superclass reference variable can refer to subclass objects. Method Overriding : The method that gets called is determined by the actual object type (not the reference type). Late Binding : The decision about which method to call is made at runtime. Dynamic Method Dispatch in Java <#> Unit - II Inheritance, Packages And Interfaces
Example of Dynamic Method DispatchLet’s consider a simple example with an Animal superclass and a couple of subclasses, Dog and Cat. We'll demonstrate how dynamic method dispatch works when invoking overridden methods. Step 1: Define the Superclass <#> Unit - II Inheritance, Packages And Interfaces class Animal { void sound() { System.out.println ("Animal makes a sound"); } } Define Subclasses class Dog extends Animal { @Override void sound() { System.out.println ("Dog barks"); } } class Cat extends Animal { @Override void sound() { System.out.println ("Cat meows"); } } public class Main { public static void main(String[] args ) { Animal myAnimal ; // Declare an Animal reference myAnimal = new Dog(); // Assign Dog object myAnimal.sound (); // Calls Dog's sound() - Dynamic Method Dispatch myAnimal = new Cat(); // Assign Cat object myAnimal.sound (); // Calls Cat's sound() - Dynamic Method Dispatch } }
Explanation of the Example Superclass Reference: In the Main class, we declare an Animal reference named myAnimal . Object Creation: First, we create a Dog object and assign it to myAnimal . When we call myAnimal.sound (), Java dynamically binds the call to the sound() method defined in the Dog class at runtime. Next, we reassign myAnimal to a new Cat object. When we call myAnimal.sound () again, the call is dynamically bound to the sound() method in the Cat class. Polymorphism: This behavior exemplifies polymorphism because the same reference variable ( myAnimal ) can invoke different method implementations based on the actual object type. <#> Unit - II Inheritance, Packages And Interfaces
Advantages of Dynamic Method Dispatch Flexibility : It provides flexibility in the code, allowing the use of base class references to work with derived class objects. Enhanced Code Reusability : It allows developers to define methods in the base class and override them in derived classes without changing the base class's implementation. Extensibility : New subclasses can be added without modifying existing code, enhancing maintainability and extensibility. <#> Unit - II Inheritance, Packages And Interfaces
An abstract class in Java is a class that cannot be instantiated on its own and may contain abstract methods (methods without a body) as well as concrete methods (methods with an implementation). Abstract classes are used to define a template for subclasses to follow. Key Points about Abstract Classes Cannot Instantiate: You cannot create an instance of an abstract class directly. Abstract Methods: An abstract class can have abstract methods that must be implemented by subclasses. Concrete Methods: An abstract class can also have concrete methods with implementations that can be inherited by subclasses. Inheritance: Abstract classes are used to achieve abstraction and can be extended by other classes. Abstract Classes in Java <#> Unit - II Inheritance, Packages And Interfaces
Example of Abstract Classes Let’s create an example that demonstrates the concept of abstract classes using a simple shape application. <#> Unit - II Inheritance, Packages And Interfaces Define an Abstract Class abstractclassShape { // Abstract method (no implementation)abstractvoiddraw(); // Concrete methodvoiddisplay() { System.out.println("Displaying the shape"); } } Define Subclasses classCircleextendsShape { @Overridevoiddraw() { System.out.println("Drawing a Circle"); } } classRectangleextendsShape { @Overridevoiddraw() { System.out.println("Drawing a Rectangle"); } }
<#> Unit - II Inheritance, Packages And Interfaces Testing Abstract Classes publicclassMain { publicstaticvoidmain(String[] args) { Shape myShape1=newCircle(); // Shape reference but Circle object Shape myShape2=newRectangle(); // Shape reference but Rectangle object myShape1.draw(); // Calls Circle's draw() myShape1.display(); // Calls Shape's display() myShape2.draw(); // Calls Rectangle's draw() myShape2.display(); // Calls Shape's display() } }
<#> Unit - II Inheritance, Packages And Interfaces Abstract Class: The Shape class is defined as an abstract class with an abstract method draw() and a concrete method display(). Subclass Implementation: Instantiation and Method Invocation: In the Main class, we create references of type Shape for both Circle and Rectangle. This demonstrates polymorphism, as we can refer to different subclasses using a single abstract class reference. We call the draw() method, which invokes the corresponding subclass implementation.
<#> Unit - II Inheritance, Packages And Interfaces Advantages of Abstract Classes Abstraction: They provide a way to define abstract methods that must be implemented by subclasses, enforcing a contract for subclasses. Reusability: Common behavior can be defined in the abstract class, allowing subclasses to inherit this functionality without duplicating code. Flexibility: New subclasses can be added with their implementations of abstract methods without changing existing code.
final Keyword in Java with Inheritance <#> Unit - II Inheritance, Packages And Interfaces In Java, the final keyword is used to restrict the user from modifying the behavior of classes, methods, and variables. Specifically, when used in conjunction with inheritance, final helps prevent method overriding and class inheritance, ensuring that certain aspects of the code remain unchangeable. Usage of final in Inheritance final Class: A class declared as final cannot be extended (inherited). This means no other class can subclass it. final Method: A method declared as final cannot be overridden by subclasses. final Variable: Once assigned, a final variable's value cannot be changed. While this isn’t directly related to inheritance, it is often used in conjunction with inheritance to create immutable states within classes.
<#> Unit - II Inheritance, Packages And Interfaces final Classes (Prevent Inheritance) A final class cannot be extended by any subclass. This ensures that the behavior of the class cannot be modified by subclassing. finalclassAnimal { voidsound() { System.out.println("Animal makes a sound"); } } // The following would cause a compile-time error:// class Dog extends Animal {// // Compilation Error: Cannot inherit from final 'Animal'// } publicclassMain { publicstaticvoidmain(String[] args) { Animalanimal=newAnimal(); animal.sound(); } } In the above example: The Animal class is declared final, meaning no other class can inherit from it. If you try to create a subclass of Animal, it will cause a compilation error.
<#> Unit - II Inheritance, Packages And Interfaces final Methods (Prevent Method Overriding) A final method in a superclass cannot be overridden by any subclass. This is useful when you want to prevent subclasses from changing the implementation of a method. classAnimal { finalvoidsound() { System.out.println("Animal makes a sound"); } } classDogextendsAnimal { // The following would cause a compile-time error:// void sound() {// System.out.println("Dog barks");// }voiddisplay() { System.out.println("Dog specific behavior"); } } publicclassMain { publicstaticvoidmain(String[] args) { Dogdog=newDog(); dog.sound(); // Calls the final method from Animal dog.display(); // Calls the Dog's own method } } The sound() method in the Animal class is marked as final, preventing the Dog class from overriding it. If you try to override sound() in the Dog class, a compilation error will occur.
<#> Unit - II Inheritance, Packages And Interfaces final Variables (Constants) While not directly related to inheritance, it is important to mention that final variables are often used in classes to create constants. final variables must be initialized once and cannot be modified afterward. classAnimal { finalintlegs=4; // Constant value, cannot be changedfinalvoidsound() { System.out.println("Animal makes a sound"); } } classDogextendsAnimal { voiddisplay() { System.out.println("Dog has " + legs + " legs"); // Accessing final variable } } publicclassMain { publicstaticvoidmain(String[] args) { Dogdog=newDog(); dog.display(); // Outputs: Dog has 4 legs } } The legs variable is declared as final in the Animal class, meaning it is a constant and its value cannot be changed. The Dog class can access the final variable, but it cannot modify it.
<#> Unit - II Inheritance, Packages And Interfaces Practical Uses of the final Keyword Preventing Changes: The final keyword is used to prevent classes or methods from being changed by subclassing or overriding, ensuring the integrity of critical code. Security: In secure applications, marking classes and methods as final prevents malicious code from altering the behavior of certain components. Immutability: By marking variables as final, you can ensure that their values remain constant throughout the lifetime of the object.
A package in Java is a mechanism for organizing Java classes, interfaces, and sub-packages. It helps in categorizing the classes and interfaces so that they can be easily maintained and accessed. Packages provide access protection and help in avoiding name conflicts between classes. Types of Packages Built-in Packages: Java provides a large number of built-in packages that contain commonly used classes, such as java.util, java.lang, java.io, etc. User-defined Packages: These are packages created by developers to group related classes and interfaces together. Packages in Java <#> Unit - II Inheritance, Packages And Interfaces
<#> Unit - II Inheritance, Packages And Interfaces Why Use Packages ? Organizing Code: Packages help in organizing code into distinct modules. Avoiding Name Conflicts: Two classes in different packages can have the same name but be differentiated by their package names. Access Control: Packages allow you to control the visibility of classes, methods, and variables, which enhances encapsulation. Reusability: Classes defined in one package can be reused in other packages through import statements .
<#> Unit - II Inheritance, Packages And Interfaces Defining a Package To define a package, the package keyword is used at the beginning of a Java source file. package com.example.mypackage; // Define a packagepublicclassMyClass { publicvoiddisplayMessage() { System.out.println("Hello from MyClass in com.example.mypackage"); } } The class MyClass belongs to the package com.example.mypackage. You must save this file in a directory structure that matches the package name, e.g., com/example/mypackage/MyClass.java.
<#> Unit - II Inheritance, Packages And Interfaces Using Packages To use a class from another package, you either need to fully qualify the class name or use an import statement to import the package. Using a Class from Another Package Suppose the following class Main is in a different package: package com.example.main; import com.example.mypackage.MyClass; // Import the MyClasspublicclassMain { publicstaticvoidmain(String[] args) { MyClassmyClass=newMyClass(); // Create object of MyClass myClass.displayMessage(); // Call method from MyClass } } We import the MyClass from the com.example.mypackage. The Main class uses the method displayMessage() from MyClass.
Built-in Packages in Java <#> Unit - II Inheritance, Packages And Interfaces Java has a number of built-in packages that provide various functionalities, such as utilities, networking, input/output (I/O), etc. Common Built-in Packages: java.lang: Contains fundamental classes like String, Math, Object, System. This package is automatically imported in every Java program. java.util: Contains utility classes like ArrayList, HashMap, Date, Collections, and more. java.io: Contains classes for input/output operations like File, BufferedReader, InputStream. java.net: Contains classes for networking like Socket, ServerSocket, URL. java.awt and javax.swing: Used for building graphical user interface (GUI) applications.
<#> Unit - II Inheritance, Packages And Interfaces import java.util.ArrayList; publicclassMain { publicstaticvoidmain(String[] args) { ArrayList<String> list = newArrayList<>(); // Using ArrayList from java.util package list.add("Hello"); list.add("World"); System.out.println(list); } }
<#> Unit - II Inheritance, Packages And Interfaces Access Control and Packages Java provides several access levels that determine the visibility of classes, methods, and fields across packages. public: The class, method, or variable can be accessed from any other class, even if it is in a different package. protected: The class, method, or variable can be accessed within the same package and by subclasses in other packages. default (Package-private): If no access modifier is specified, the class, method, or variable is accessible only within the same package. private: The class, method, or variable is accessible only within the same class and not outside.
<#> Unit - II Inheritance, Packages And Interfaces package com.example.access; public classParentClass { public voidpublicMethod() { System.out.println("Public method"); } protectedvoidprotectedMethod() { System.out.println("Protected method"); } void defaultMethod() { System.out.println("Default method (package-private)"); } private voidprivateMethod() { System.out.println("Private method"); } } publicMethod() can be accessed from any class in any package. protectedMethod() can be accessed by subclasses or classes within the same package. defaultMethod() can be accessed only by classes within the same package. privateMethod() can only be accessed within ParentClass.
<#> Unit - II Inheritance, Packages And Interfaces Sub-packages Java allows you to create sub-packages. A sub-package is a package inside another package. package com.example.subpackage; publicclassSubClass { publicvoiddisplay() { System.out.println("Hello from SubClass in subpackage"); } } The class SubClass is part of the sub-package com.example.subpackage. When using this class in another package, you would import it like: import com.example.subpackage.SubClass;
<#> Unit - II Inheritance, Packages And Interfaces Static Imports In addition to importing classes, you can also import static methods and fields using the static import statement. This allows you to use static members of a class without fully qualifying their name. importstatic java.lang.Math.*; // Import all static members of Math classpublicclassMain { publicstaticvoidmain(String[] args) { System.out.println(sqrt(16)); // Directly using Math.sqrt() System.out.println(PI); // Directly using Math.PI } } Packages in Java help in organizing code, avoiding name conflicts, and improving modularity. Java provides both built-in packages (like java.util, java.io) and user-defined packages, which can be created by developers. Packages also help in controlling access levels through various access modifiers (public, protected, default, private). Sub-packages and static imports add flexibility and efficiency when working with packages.
Importing Packages <#> Unit - II Inheritance, Packages And Interfaces In Java, importing packages allows you to use classes from different libraries or packages without needing to specify their full package name each time. To import a package, you use the import keyword. Importing a Specific Class: If you only need a specific class from a package, you can import just that class. Syntax : import java.util.Scanner; Importing All Classes in a Package: If you want to import all classes from a package, you can use a wildcard (*). import java.util.*;
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a Scanner object System.out.println("Enter your name:"); String name = scanner.nextLine(); // Read user input System.out.println("Hello, " + name); // Output user input } } an example where we import the Scanner class to take input from the user. <#> Unit - II Inheritance, Packages And Interfaces
In Java, an interface is a abstract concept that defines a contract or a blueprint of a class. It defines a set of methods that must be implemented by any class that implements it. Interfaces are used to achieve abstraction and polymorphism in object-oriented programming. Interfaces in Java <#> Unit - II Inheritance, Packages And Interfaces key features of interfaces in Java: Abstract: An interface is abstract, meaning it cannot be instantiated on its own. It can only be implemented by a class. Methods: An interface can contain only abstract methods, which are methods that do not have a body and are declared using the abstract keyword. No Implementation: An interface does not provide any implementation for its methods. It is up to the implementing class to provide the implementation.
Multiple Inheritance: A class can implement multiple interfaces, but it can only extend one class. Method Signatures: Interfaces can only define method signatures (i.e., the method name, return type, and parameter list). The implementation of the method is provided by the implementing class. Static Methods: Interfaces can also contain static methods, which are methods that can be called without creating an instance of the interface. Constants: Interfaces can also contain constants, which are public, static, and final variables. <#> Unit - II Inheritance, Packages And Interfaces public interface Printable { void print(); } In this example, the Printable interface defines a single abstract method print(), which must be implemented by any class that implements it.
public class Document implements Printable { public void print() { System.out.println("Printing a document"); } } <#> Unit - II Inheritance, Packages And Interfaces In this example, the Document class implements the Printable interface by providing an implementation for the print() method.
Abstraction: Interfaces allow you to define an abstract contract that must be implemented by any class that implements it. Polymorphism: Interfaces enable polymorphism, which allows you to treat objects of different classes as if they were of the same type. Decoupling: Interfaces help to decouple classes from each other, making it easier to change or replace one class without affecting others. Benefits of interface <#> Unit - II Inheritance, Packages And Interfaces
Defining a contract : Use interfaces to define a contract that must be implemented by any class that implements it. Providing polymorphism: Use interfaces to enable polymorphism, allowing you to treat objects of different classes as if they were of the same type. Defining a set of methods: Use interfaces to define a set of methods that must be implemented by any class that implements it. common use cases for interface <#> Unit - II Inheritance, Packages And Interfaces
Use meaningful names: Use meaningful names for your interfaces and methods to make them easy to understand. Keep interfaces simple: Keep interfaces simple and focused on a single concept or functionality. Use interfaces judiciously: Use interfaces judiciously and only when necessary, as they can add complexity to your code. best practices for using interface <#> Unit - II Inheritance, Packages And Interfaces