R22 OOPTJ Unit2 Notes UPDATED.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

R22 - OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-2 Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype, substitutability, forms of inheritance specialization, specification, construction, extension, limitation, combinati...

R22 - OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-2 Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype, substitutability, forms of inheritance specialization, specification, construction, extension, limitation, combination, benefits of inheritance, costs of inheritance. Member Access rules, super uses, using final with inheritance, polymorphism, method overriding, abstract classes, the Object class. Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing packages, differences between classes and interfaces, defining an interface, implementing interface, applying interfaces, variables in interface and extending interfaces. Exploring java.io. Abstractions in Java Abstraction in Java is the process in which we only show essential details/functionality to the user. The non-essential implementation details are not displayed to the user. Simple Example to understand Abstraction: Television remote control is an excellent example of abstraction. It simplifies the interaction with a TV by hiding the complexity behind simple buttons and symbols, making it easy without needing to understand the technical details of how the TV functions. In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. Abstraction Real-Life Example: Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is. Abstract classes and Abstract methods 1. An abstract class is a class that is declared with an abstract keyword. 2. An abstract method is a method that is declared without implementation. 3. An abstract class may or may not have all abstract methods. Some of them can be concrete methods 4. A method-defined abstract must always be redefined in the subclass, thus making overriding compulsory or making the subclass itself abstract. 5. Any class that contains one or more abstract methods must also be declared with an abstract keyword. 6. There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator. 7. An abstract class can have parameterized constructors and the default constructor is always present in an abstract class. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 1 Forms of Inheritance The inheritance concept used for the number of purposes in the java programming language. One of the main purposes is substitutability. The substitutability means that when a child class acquires properties from its parent class, the object of the parent class may be substituted with the child class object. For example, if B is a child class of A, anywhere we expect an instance of A we can use an instance of B. The substitutability can achieve using inheritance, whether using extends or implements keywords. The following are the different forms of inheritance in java.  Specialization  Specification  Construction  Extension  Limitation  Combination Specialization It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the principle of substitutability. Specification This is another commonly used form of inheritance. In this form of inheritance, the parent class just specifies which methods should be available to the child class but doesn't implement them. The java provides concepts like abstract and interfaces to support this form of inheritance. It holds the principle of substitutability. Construction This is another form of inheritance where the child class may change the behavior defined by the parent class (overriding). It does not hold the principle of substitutability. Extension This is another form of inheritance where the child class may add its new properties. It holds the principle of substitutability. Limitation This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold the principle of substitutability. Combination This is another form of inheritance where the subclass inherits properties from multiple parent classes. Java does not support multiple inheritance type. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 2 Benefits and Costs of Inheritance in java The inheritance is the core and more useful concept Object Oriented Programming. In inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs. Provides lot of benefits and few of them are listed below. Benefits of Inheritance  Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it.  Inheritance can save time and effort as the main code need not be written again.  Inheritance provides a clear model structure which is easy to understand.  An inheritance leads to less development and maintenance costs.  With inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs.  In inheritance base class can decide to keep some data private so that it cannot be altered by the derived class. Costs of Inheritance  Inheritance decreases the execution speed due to the increased time and effort it takes, the program to jump through all the levels of overloaded classes.  Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one cannot be used independently of each other.  The changes made in the parent class will affect the behavior of child class too.  The overuse of inheritance makes the program more complex. Java Inheritance The inheritance is a very useful and powerful concept of object-oriented programming. In java, using the inheritance concept, we can use the existing features of one class in another class. The inheritance provides a great advantage called code re-usability. With the help of code re- usability, the commonly used code in an application need not be written again and again. The inheritance is the process of acquiring the properties of one class to another class. Inheritance Basics In inheritance, we use the terms like parent class, child class, base class, derived class, superclass, and subclass. The Parent class is the class which provides features to another class. The parent class is also known as Base class or Superclass. The Child class is the class which receives features from another class. The child class is also known as the Derived Class or Subclass. In the inheritance, the child class acquires the features from its parent class. But the parent class never acquires the features from its child class. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 3 There are five types of inheritances, and they are as follows.  Simple Inheritance (or) Single Inheritance  Multiple Inheritance  Multi-Level Inheritance  Hierarchical Inheritance  Hybrid Inheritance The following picture illustrates how various inheritances are implemented. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 4 The java programming language does not support multiple inheritance type. However, it provides an alternate with the concept of interfaces. Creating Child Class in java In java, we use the keyword extends to create a child class. The following syntax used to create a child class in java. Syntax class extends {... //Implementation of child class... } In a java programming language, a class extends only one class. Extending multiple classes is not allowed in java. Single Inheritance in java In this type of inheritance, one child class derives from one parent class. Look at the following example code. class ParentClass{ int a; void setData(int a) { this.a = a; } } class ChildClass extends ParentClass{ void showData() { System.out.println("Value of a is " + a); } } public class SingleInheritance { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.setData(100); obj.showData(); } } Multi-level Inheritance in java In this type of inheritance, the child class derives from a class which already derived from another class. Look at the following example java code. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 5 class ParentClass{ int a; void setData(int a) { this.a = a; } } class ChildClass extends ParentClass{ void showData() { System.out.println("Value of a is " + a); } } class ChildChildClass extends ChildClass{ void display() { System.out.println("Inside ChildChildClass!"); } } public class MultipleInheritance { public static void main(String[] args) { ChildChildClass obj = new ChildChildClass(); obj.setData(100); obj.showData(); obj.display(); } } Hierarchical Inheritance in java In this type of inheritance, two or more child classes derive from one parent class. Look at the following example java code. class ParentClass{ R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 6 int a; void setData(int a) { this.a = a; } } class ChildClass extends ParentClass{ void showData() { System.out.println("Inside ChildClass!"); System.out.println("Value of a is " + a); } } class ChildClassToo extends ParentClass{ void display() { System.out.println("Inside ChildClassToo!"); System.out.println("Value of a is " + a); } } public class HierarchicalInheritance { public static void main(String[] args) { ChildClass child_obj = new ChildClass(); child_obj.setData(100); child_obj.showData(); ChildClassToo childToo_obj = new ChildClassToo(); childToo_obj.setData(200); childToo_obj.display(); } } Hybrid Inheritance in java The hybrid inheritance is the combination of more than one type of inheritance. We may use any combination as a single with multiple inheritances, multi-level with multiple inheritances, etc. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 7 Java Access Modifiers In Java, the access specifiers (also known as access modifiers) used to restrict the scope or accessibility of a class, constructor, variable, method or data member of class and interface. There are four access specifiers, and their list is below.  default (or) no modifier  public  protected  private In java, we cannot employ all access specifiers on everything. The following table describes where we can apply the access specifiers. Let's look at the following example java code, which generates an error because a class does not allow private access specifier unless it is an inner class. private class Sample{... } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 8 In java, the accessibility of the members of a class or interface depends on its access specifiers. The following table provides information about the visibility of both data members and methods.  The public members can be accessed everywhere.  The private members can be accessed only inside the same class.  The protected members are accessible to every child class (same package or other packages).  The default members are accessible within the same package but not outside the package. Let's look at the following example java code. class ParentClass{ int a = 10; public int b = 20; protected int c = 30; private int d = 40; void showData() { System.out.println("Inside ParentClass"); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 9 class ChildClass extends ParentClass{ void accessData() { System.out.println("Inside ChildClass"); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); //System.out.println("d = " + d); // private member can't be accessed } } public class AccessModifiersExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.showData(); obj.accessData(); } } Java Constructors in Inheritance It is very important to understand how the constructors get executed in the inheritance concept. In the inheritance, the constructors never get inherited to any child class. In java, the default constructor of a parent class called automatically by the constructor of its child class. That means when we create an object of the child class, the parent class constructor executed, followed by the child class constructor executed. Let's look at the following example java code. class ParentClass{ int a; ParentClass(){ System.out.println("Inside ParentClass constructor!"); } } class ChildClass extends ParentClass{ ChildClass(){ System.out.println("Inside ChildClass constructor!!"); R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 10 } } class ChildChildClass extends ChildClass{ ChildChildClass(){ System.out.println("Inside ChildChildClass constructor!!"); } } public class ConstructorInInheritance { public static void main(String[] args) { ChildChildClass obj = new ChildChildClass(); } } However, if the parent class contains default and parameterized constructor, then only the default constructor called automatically by the child class constructor. Let's look at the following example java code. class ParentClass{ int a; ParentClass(int a){ System.out.println("Inside ParentClass parameterized constructor!"); this.a = a; } ParentClass(){ System.out.println("Inside ParentClass default constructor!"); } } class ChildClass extends ParentClass{ ChildClass(){ System.out.println("Inside ChildClass constructor!!"); R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 11 } } public class ConstructorInInheritance { public static void main(String[] args) { ChildClass obj = new ChildClass(); } } The parameterized constructor of parent class must be called explicitly using the super keyword. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 12 Java super keyword In java, super is a keyword used to refer to the parent class object. The super keyword came into existence to solve the naming conflicts in the inheritance. When both parent class and child class have members with the same name, then the super keyword is used to refer to the parent class version. In java, the super keyword is used for the following purposes.  To refer parent class data members  To refer parent class methods  To call parent class constructor The super keyword is used inside the child class only. super to refer parent class data members When both parent class and child class have data members with the same name, then the super keyword is used to refer to the parent class data member from child class. Let's look at the following example java code. class ParentClass{ int num = 10; } class ChildClass extends ParentClass{ int num = 20; void showData() { System.out.println("Inside the ChildClass"); System.out.println("ChildClass num = " + num); System.out.println("ParentClass num = " + super.num); } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 13 public class SuperKeywordExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.showData(); System.out.println("\nInside the non-child class"); System.out.println("ChildClass num = " + obj.num); //System.out.println("ParentClass num = " + super.num); //super can't be used here } } super to refer parent class method When both parent class and child class have method with the same name, then the super keyword is used to refer to the parent class method from child class. Let's look at the following example java code. class ParentClass{ int num1 = 10; void showData() { System.out.println("\nInside the ParentClass showData method"); System.out.println("ParentClass num = " + num1); } } class ChildClass extends ParentClass{ int num2 = 20; void showData() { System.out.println("\nInside the ChildClass showData method"); System.out.println("ChildClass num = " + num2); super.showData(); } } public class SuperKeywordExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.showData(); //super.showData(); // super can't be used here R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 14 } } super to call parent class constructor When an object of child class is created, it automatically calls the parent class default- constructor before its own. But, the parameterized constructor of parent class must be called explicitly using the super keyword inside the child class constructor. class ParentClass { int num1; ParentClass(){ System.out.println("\nInside the ParentClass default constructor"); num1 = 10; } ParentClass(int value) { System.out.println("\nInside the ParentClass parameterized constructor"); num1 = value; } } class ChildClass extends ParentClass{ int num2; ChildClass(){ super(100); System.out.println("\nInside the ChildClass constructor"); num2 = 200; } } public class SuperKeywordExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); } } To call the parameterized constructor of the parent class, the super keyword must be the first statement inside the child class constructor, and we must pass the parameter values. Java final keyword R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 15 In java, the final is a keyword and it is used with the following things.  With variable (to create constant)  With method (to avoid method overriding)  With class (to avoid inheritance) final with variables When a variable defined with the final keyword, it becomes a constant, and it does not allow us to modify the value. The variable defined with the final keyword allows only a one-time assignment, once a value assigned to it, never allows us to change it again. Let's look at the following example java code. public class FinalVariableExample { public static void main(String[] args) { final int a = 10; System.out.println("a = " + a); a = 100; // Can't be modified } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 16 final with methods When a method defined with the final keyword, it does not allow it to override. The final method extends to the child class, but the child class cannot override or re-define it. It must be used as it has implemented in the parent class. Let's look at the following example java code. class ParentClass{ int num = 10; final void showData() { System.out.println("Inside ParentClass showData() method"); System.out.println("num = " + num); } } class ChildClass extends ParentClass{ void showData() { System.out.println("Inside ChildClass showData() method"); System.out.println("num = " + num); } } public class FinalKeywordExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.showData(); } } final with class When a class defined with final keyword, it cannot be extended by any other class. Let's look at the following example java code. final class ParentClass{ int num = 10; void showData() { System.out.println("Inside ParentClass showData() method"); System.out.println("num = " + num); } } class ChildClass extends ParentClass{ } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 17 public class FinalKeywordExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); } } Java Polymorphism The polymorphism is the process of defining same method with different implementation. That means creating multiple methods with different behaviors. In java, polymorphism implemented using method overloading and method overriding. Ad hoc polymorphism or Compile time polymorphism The ad hoc polymorphism is a technique used to define the same method with different implementations and different arguments. In a java programming language, ad hoc polymorphism carried out with a method overloading concept. In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc polymorphism is also known as compile-time polymorphism. Every function call binded with the respective overloaded method based on the arguments. The ad hoc polymorphism implemented within the class only. import java.util.Arrays; public class AdHocPolymorphismExample { void sorting(int[] list) { Arrays.parallelSort(list); System.out.println("Integers after sort: " + Arrays.toString(list) ); } void sorting(String[] names) { Arrays.parallelSort(names); System.out.println("Names after sort: " + Arrays.toString(names) ); } public static void main(String[] args) { AdHocPolymorphismExample obj = new AdHocPolymorphismExample(); int list[] = {2, 3, 1, 5, 4}; obj.sorting(list); // Calling with integer array String[] names = {"rama", "raja", "shyam", "seeta"}; R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 18 obj.sorting(names); // Calling with String array } } Pure polymorphism or Run time polymorphism The pure polymorphism is a technique used to define the same method with the same arguments but different implementations. In a java programming language, pure polymorphism carried out with a method overriding concept. In pure polymorphism, the method binding happens at run time. Pure polymorphism is also known as run-time polymorphism. Every function call binding with the respective overridden method based on the object reference. When a child class has a definition for a member function of the parent class, the parent class function is said to be overridden. The pure polymorphism implemented in the inheritance concept only. Let's look at the following example java code. class ParentClass{ int num = 10; void showData() { System.out.println("Inside ParentClass showData() method"); System.out.println("num = " + num); } } class ChildClass extends ParentClass{ void showData() { System.out.println("Inside ChildClass showData() method"); System.out.println("num = " + num); } } public class PurePolymorphism { public static void main(String[] args) { ParentClass obj = new ParentClass(); obj.showData(); obj = new ChildClass(); obj.showData(); } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 19 Java Abstract Class An abstract class is a class that created using abstract keyword. In other words, a class prefixed with abstract keyword is known as an abstract class. In java, an abstract class may contain abstract methods (methods without implementation) and also non-abstract methods (methods with implementation). We use the following syntax to create an abstract class. abstract class {... } Let's look at the following example java code. import java.util.*; abstract class Shape { int length, breadth, radius; Scanner input = new Scanner(System.in); abstract void printArea(); } class Rectangle extends Shape { void printArea() { System.out.println("*** Finding the Area of Rectangle ***"); System.out.print("Enter length and breadth: "); length = input.nextInt(); breadth = input.nextInt(); System.out.println("The area of Rectangle is: " + length * breadth); } } class Triangle extends Shape { void printArea() { System.out.println("\n*** Finding the Area of Triangle ***"); System.out.print("Enter Base And Height: "); length = input.nextInt(); breadth = input.nextInt(); System.out.println("The area of Triangle is: " + (length * breadth) / 2); } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 20 class Cricle extends Shape { void printArea() { System.out.println("\n*** Finding the Area of Cricle ***"); System.out.print("Enter Radius: "); radius = input.nextInt(); System.out.println("The area of Cricle is: " + 3.14f * radius * radius); } } public class AbstractClassExample { public static void main(String[] args) { Rectangle rec = new Rectangle(); rec.printArea(); Triangle tri = new Triangle(); tri.printArea(); Cricle cri = new Cricle(); cri.printArea(); } } An abstract class cannot be instantiated but can be referenced. That means we cannot create an object of an abstract class, but base reference can be created. In the above example program, the child class objects are created to invoke the overridden abstract method. But we may also create base class reference and assign it with child class instance to invoke the same. The main method of the above program can be written as follows that produce the same output. public static void main(String[] args) { Shape obj = new Rectangle(); //Base class reference to Child class instance obj.printArea(); obj = new Triangle(); obj.printArea(); obj = new Cricle(); obj.printArea(); } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 21 Rules for method overriding An abstract class must follow the below list of rules.  An abstract class must be created with abstract keyword.  An abstract class can be created without any abstract method.  An abstract class may contain abstract methods and non-abstract methods.  An abstract class may contain final methods that cannot be overridden.  An abstract class may contain static methods, but the abstract method cannot be static.  An abstract class may have a constructor that gets executed when the child class object created.  An abstract method must be overridden by the child class; otherwise, it must be defined as an abstract class.  An abstract class cannot be instantiated but can be referenced. Java Object Class In java, the Object class is the super most class of any class hierarchy. The Object class in the java programming language is present inside the java.lang package. Every class in the java programming language is a subclass of Object class by default. The Object class is useful when you want to refer to any object whose type you don't know. Because it is the superclass of all other classes in java, it can refer to any type of object. Methods of Object class The following table depicts all built-in methods of Object class in java. Return Method Description Value getClass() Returns Class object object hashCode() Returns the hash code number for object being used. int equals(Object obj) Compares the argument object to calling object. boolean clone() Compares two strings, ignoring case int concat(String) Creates copy of invoking object object toString() Returns the string representation of invoking object. String notify() Wakes up a thread, waiting on invoking object's monitor. void Wakes up all the threads, waiting on invoking object's notifyAll() void monitor. Causes the current thread to wait, until another thread wait() void notifies. Causes the current thread to wait for the specified wait(long,int) milliseconds and nanoseconds, until another thread void notifies. It is invoked by the garbage collector before an object is finalize() void being garbage collected. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 22 Packages & Interfaces In java, a package is a container of classes, interfaces, and sub-packages. We may think of it as a folder in a file directory. We use the packages to avoid naming conflicts and to organize project-related classes, interfaces, and sub-packages into a bundle. In java, the packages have divided into two types.  Built-in Packages  User-defined Packages Built-in Packages The built-in packages are the packages from java API. The Java API is a library of pre-defined classes, interfaces, and sub-packages. The built-in packages were included in the JDK. There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax, swing, net, sql, etc. We need to import the built-in packages to use them in our program. To import a package, we use the import statement. User-defined Packages The user-defined packages are the packages created by the user. User is free to create their own packages. Definig a Package in java We use the package keyword to create or define a package in java programming language. Syntax package packageName;  The package statement must be the first statement in the program.  The package name must be a single word.  The package name must use Camel case notation. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 23 Let's consider the following code to create a user-defined package myPackage. package myPackage; public class DefiningPackage { public static void main(String[] args) { System.out.println("This class belongs to myPackage."); } } Now, save the above code in a file DefiningPackage.java, and compile it using the following command. javac -d. DefiningPackage.java The above command creates a directory with the package name myPackage, and the DefiningPackage.class is saved into it. Run the program use the following command. java myPackage.DefiningPackage  When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically. Access protection in java packages In java, the access modifiers define the accessibility of the class and its members. For example, private members are accessible within the same class members only. Java has four access modifiers, and they are default, private, protected, and public. In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The class acts as a container of data and methods. So, the access modifier decides the accessibility of class members across the different packages. In java, the accessibility of the members of a class or interface depends on its access specifiers. The following table provides information about the visibility of both data members and methods. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 24  The public members can be accessed everywhere.  The private members can be accessed only inside the same class.  The protected members are accessible to every child class (same package or other packages).  The default members are accessible within the same package but not outside the package. Let's look at the following example java code. class ParentClass{ int a = 10; public int b = 20; protected int c = 30; private int d = 40; void showData() { System.out.println("Inside ParentClass"); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } } class ChildClass extends ParentClass{ void accessData() { System.out.println("Inside ChildClass"); System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); //System.out.println("d = " + d); // private member can't be accessed } } public class AccessModifiersExample { public static void main(String[] args) { ChildClass obj = new ChildClass(); R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 25 obj.showData(); obj.accessData(); } } Importing Packages in java In java, the import keyword used to import built-in and user-defined packages. When a package has imported, we can refer to all the classes of that package using their name directly. The import statement must be after the package statement, and before any other statement. Using an import statement, we may import a specific class or all the classes from a package.  Using one import statement, we may import only one package or a class.  Using an import statement, we cannot import a class directly, but it must be a part of a package.  A program may contain any number of import statements. Importing specific class Using an importing statement, we can import a specific class. The following syntax is employed to import a specific class. import packageName.ClassName; Let's look at an import statement to import a built-in package and Scanner class. package myPackage; import java.util.Scanner; public class ImportingExample { public static void main(String[] args) { Scanner read = new Scanner(System.in); int i = read.nextInt(); System.out.println("You have entered a number " + i); } } In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class called Scanner from java.util package. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 26 Importing all the classes Using an importing statement, we can import all the classes of a package. To import all the classes of the package, we use * symbol. The following syntax is employed to import all the classes of a package. import packageName.*; Let's look at an import statement to import a built-in package. package myPackage; import java.util.*; public class ImportingExample { public static void main(String[] args) { Scanner read = new Scanner(System.in); int i = read.nextInt(); System.out.println("You have entered a number " + i); Random rand = new Random(); int num = rand.nextInt(100); System.out.println("Randomly generated number " + num); } } In the above code, the class ImportingExample belongs to myPackage package, and it also importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.  The import statement imports only classes of the package, but not sub-packages and its classes.  We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-package. Consider the following import statement. import java.util.*; The above import statement util is a sub-package of java package. It imports all the classes of util package only, but not classes of java package. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 27 Defining an interface in java In java, an interface is similar to a class, but it contains abstract methods and static final variables only. The interface in Java is another mechanism to achieve abstraction. We may think of an interface as a completely abstract class. None of the methods in the interface has an implementation, and all the variables in the interface are constants. All the methods of an interface, implemented by the class that implements it. The interface in java enables java to support multiple-inheritance. An interface may extend only one interface, but a class may implement any number of interfaces.  An interface is a container of abstract methods and static final variables.  An interface, implemented by a class. (class implements interface).  An interface may extend another interface. (Interface extends Interface).  An interface never implements another interface, or class.  A class may implement any number of interfaces.  We cannot instantiate an interface.  Specifying the keyword abstract for interface methods is optional, it automatically added.  All the members of an interface are public by default. Defining an interface in java Defining an interface is similar to that of a class. We use the keyword interface to define an interface. All the members of an interface are public by default. The following is the syntax for defining an interface. interface InterfaceName{... members declaration;... } Let's look at an example code to define an interface. interface HumanInterfaceExample { void learn(String str); void work(); int duration = 10; } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 28 In the above code defines an interface HumanInterfaceExample that contains two abstract methods learn(), work() and one constant duration. Every interface in Java is auto-completed by the compiler. For example, in the above example code, no member is defined as public, but all are public automatically. The above code automatically converted as follows. interface HumanInterfaceExample { public abstract void learn(String str); public abstract void work(); public static final int duration = 10; } Implementing an Interface in java In java, an interface is implemented by a class. The class that implements an interface must provide code for all the methods defined in the interface, otherwise, it must be defined as an abstract class. The class uses a keyword implements to implement an interface. A class can implement any number of interfaces. When a class wants to implement more than one interface, we use the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. The following is the syntax for defineing a class that implements an interface. class className implements InterfaceName{... boby-of-the-class... } Let's look at an example code to define a class that implements an interface. interface Human { void learn(String str); void work(); int duration = 10; } class Programmer implements Human{ R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 29 public void learn(String str) { System.out.println("Learn using " + str); } public void work() { System.out.println("Develop applications"); } } public class HumanTest { public static void main(String[] args) { Programmer trainee = new Programmer(); trainee.learn("coding"); trainee.work(); } } In the above code defines an interface Human that contains two abstract methods learn(), work() and one constant duration. The class Programmer implements the interface. As it implementing the Human interface it must provide the body of all the methods those defined in the Human interface. Implementing multiple Interfaces When a class wants to implement more than one interface, we use the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. The following is the syntax for defineing a class that implements multiple interfaces. class className implements InterfaceName1, InterfaceName2,...{... boby-of-the-class... } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 30 Let's look at an example code to define a class that implements multiple interfaces. interface Human { void learn(String str); void work(); } interface Recruitment { boolean screening(int score); boolean interview(boolean selected); } class Programmer implements Human, Recruitment { public void learn(String str) { System.out.println("Learn using " + str); } public boolean screening(int score) { System.out.println("Attend screening test"); int thresold = 20; if(score > thresold) return true; return false; } public boolean interview(boolean selected) { System.out.println("Attend interview"); if(selected) return true; return false; } public void work() { System.out.println("Develop applications"); } } public class HumanTest { R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 31 public static void main(String[] args) { Programmer trainee = new Programmer(); trainee.learn("Coding"); trainee.screening(30); trainee.interview(true); trainee.work(); } } In the above code defines two interfaces Human and Recruitment, and a class Programmer implements both the interfaces. Nested Interfaces in java In java, an interface may be defined inside another interface, and also inside a class. The interface that defined inside another interface or a class is known as nested interface. The nested interface is also referred as inner interface.  The nested interface declared within an interface is public by default.  The nested interface declared within a class can be with any access modifier.  Every nested interface is static by default. The nested interface cannot be accessed directly. We can only access the nested interface by using outer interface or outer class name followed by dot(. ), followed by the nested interface name. Nested interface inside another interface The nested interface that defined inside another interface must be accessed as OuterInterface.InnerInterface. Let's look at an example code to illustrate nested interfaces inside another interface. interface OuterInterface{ void outerMethod(); interface InnerInterface{ void innerMethod(); } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 32 class OnlyOuter implements OuterInterface{ public void outerMethod() { System.out.println("This is OuterInterface method"); } } class OnlyInner implements OuterInterface.InnerInterface{ public void innerMethod() { System.out.println("This is InnerInterface method"); } } public class NestedInterfaceExample { public static void main(String[] args) { OnlyOuter obj_1 = new OnlyOuter(); OnlyInner obj_2 = new OnlyInner(); obj_1.outerMethod(); obj_2.innerMethod(); } } Nested interface inside a class The nested interface that defined inside a class must be accessed as ClassName.InnerInterface. Let's look at an example code to illustrate nested interfaces inside a class. class OuterClass{ interface InnerInterface{ void innerMethod(); } } class ImplementingClass implements OuterClass.InnerInterface{ public void innerMethod() { System.out.println("This is InnerInterface method"); } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 33 } public class NestedInterfaceExample { public static void main(String[] args) { ImplementingClass obj = new ImplementingClass(); obj.innerMethod(); } } Variables in Java Interfaces In java, an interface is a completely abstract class. An interface is a container of abstract methods and static final variables. The interface contains the static final variables. The variables defined in an interface cannot be modified by the class that implements the interface, but it may use as it defined in the interface.  The variable in an interface is public, static, and final by default.  If any variable in an interface is defined without public, static, and final keywords then, the compiler automatically adds the same.  No access modifier is allowed except the public for interface variables.  Every variable of an interface must be initialized in the interface itself.  The class that implements an interface cannot modify the interface variable, but it may use as it defined in the interface. Let's look at an example code to illustrate variables in an interface. interface SampleInterface{ int UPPER_LIMIT = 100; //int LOWER_LIMIT; // Error - must be initialised } public class InterfaceVariablesExample implements SampleInterface{ public static void main(String[] args) { System.out.println("UPPER LIMIT = " + UPPER_LIMIT); // UPPER_LIMIT = 150; // Can not be modified } } Extending an Interface in java In java, an interface can extend another interface. When an interface wants to extend another interface, it uses the keyword extends. The interface that extends another interface has its own R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 34 members and all the members defined in its parent interface too. The class which implements a child interface needs to provide code for the methods defined in both child and parent interfaces, otherwise, it needs to be defined as abstract class.  An interface can extend another interface.  An interface cannot extend multiple interfaces.  An interface can implement neither an interface nor a class.  The class that implements child interface needs to provide code for all the methods defined in both child and parent interfaces. Let's look at an example code to illustrate extending an interface. interface ParentInterface{ void parentMethod(); } interface ChildInterface extends ParentInterface{ void childMethod(); } class ImplementingClass implements ChildInterface{ public void childMethod() { System.out.println("Child Interface method!!"); } public void parentMethod() { System.out.println("Parent Interface mehtod!"); } } public class ExtendingAnInterface { public static void main(String[] args) { ImplementingClass obj = new ImplementingClass(); obj.childMethod(); obj.parentMethod(); } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 35 Streams in java In java, the IO operations are performed using the concept of streams. Generally, a stream means a continuous flow of data. In java, a stream is a logical container of data that allows us to read from and write to it. A stream can be linked to a data source, or data destination, like a console, file or network connection by java IO system. The stream-based IO operations are faster than normal IO operations. The Stream is defined in the java.io package. To understand the functionality of java streams, look at the following picture. In java, the stream-based IO operations are performed using two separate streams input stream and output stream. The input stream is used for input operations, and the output stream is used for output operations. The java stream is composed of bytes. In Java, every program creates 3 streams automatically, and these streams are attached to the console.  System.out: standard output stream for console output operations.  System.in: standard input stream for console input operations.  System.err: standard error stream for console error output operations. The Java streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Java provides two types of streams, and they are as follows.  Byte Stream  Character Stream R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 36 The following picture shows how streams are categorized, and various built-in classes used by the java IO system. Both character and byte streams essentially provides a convenient and efficient way to handle data streams in Java. Byte Stream in java In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data. In Java 1.0 version all IO operations were byte oriented, there was no other stream (character stream). The java byte stream is defined by two abstract classes, InputStream and OutputStream. The InputStream class used for byte stream based input operations, and the OutputStream class used for byte stream based output operations. The InputStream and OutputStream classes have several concrete classes to perform various IO operations based on the byte stream. The following picture shows the classes used for byte stream operations. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 37 InputStream class The InputStream class has defined as an abstract class, and it has the following methods which have implemented by its concrete classes. S.No. Method with Description int available() 1 It returns the number of bytes that can be read from the input stream. int read() 2 It reads the next byte from the input stream. int read(byte[] b) 3 It reads a chunk of bytes from the input stream and store them in its byte array, b. void close() 4 It closes the input stream and also frees any resources connected with this input stream. OutputStream class The OutputStream class has defined as an abstract class, and it has the following methods which have implemented by its concrete classes. S.No. Method with Description void write(int n) 1 It writes byte(contained in an int) to the output stream. void write(byte[] b) 2 It writes a whole byte array(b) to the output stream. void flush() 3 It flushes the output steam by forcing out buffered bytes to be written out. void close() 4 It closes the output stream and also frees any resources connected with this output stream. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 38 Reading data using BufferedInputStream We can use the BufferedInputStream class to read data from the console. The BufferedInputStream class use a method read( ) to read a value from the console, or file, or socket. Example 1 - Reading from console import java.io.*; public class ReadingDemo { public static void main(String[] args) throws IOException { BufferedInputStream read = new BufferedInputStream(System.in); try { System.out.print("Enter any character: "); char c = (char)read.read(); System.out.println("You have entered '" + c + "'"); } catch(Exception e) { System.out.println(e); } finally { read.close(); } } } Example 2 - Reading from a file import java.io.*; public class ReadingDemo { public static void main(String[] args) throws IOException { FileInputStream fileInputStream = new FileInputStream(new File("C:\\JNTU\\dataFile.txt")); BufferedInputStream input = new BufferedInputStream(fileInputStream); try { char c = (char)input.read(); System.out.println("Data read from a file - '" + c + "'"); } catch(Exception e) { System.out.println(e); } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 39 finally { input.close(); } } } Writing data using BufferedOutputStream We can use the BufferedOutputStream class to write data into the console, file, socket. The BufferedOutputStream class use a method write( ) to write data. Example - Writing data into a file import java.io.*; public class WritingDemo { public static void main(String[] args) throws IOException { String data = "Java tutorials by BTech Smart Class"; BufferedOutputStream out = null; try { FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\JNTU\\dataFile.txt")); out = new BufferedOutputStream(fileOutputStream); out.write(data.getBytes()); System.out.println("Writing data into a file is success!"); } catch(Exception e) { System.out.println(e); } finally { out.close(); } } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 40 Character Stream in java In java, when the IO stream manages 16-bit Unicode characters, it is called a character stream. The unicode set is basically a type of character set where each character corresponds to a specific numeric value within the given character set, and every programming language has a character set. In java, the character stream is a 16 bits carrier. The character stream in java allows us to transmit 16 bits of data. The character stream was introduced in Java 1.1 version. The charater stream The java character stream is defined by two abstract classes, Reader and Writer. The Reader class used for character stream based input operations, and the Writer class used for character stream based output operations. The Reader and Writer classes have several concrete classes to perform various IO operations based on the character stream. The following picture shows the classes used for character stream operations. R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 41 Reader class The Reader class has defined as an abstract class, and it has the following methods which have implemented by its concrete classes. S.No. Method with Description int read() 1 It reads the next character from the input stream. int read(char[] cbuffer) 2 It reads a chunk of charaters from the input stream and store them in its byte array, cbuffer. int read(char[] cbuf, int off, int len) 3 It reads charaters into a portion of an array. int read(CharBuffer target) 4 It reads charaters into into the specified character buffer. String readLine() 5 It reads a line of text. A line is considered to be terminated by any oneof a line feed ('\n'), a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed. boolean ready() 6 It tells whether the stream is ready to be read. void close() 7 It closes the input stream and also frees any resources connected with this input stream. Writer class The Writer class has defined as an abstract class, and it has the following methods which have implemented by its concrete classes. S.No. Method with Description 1 void flush() It flushes the output steam by forcing out buffered bytes to be written out. 2 void write(char[] cbuf) It writes a whole array(cbuf) to the output stream. 3 void write(char[] cbuf, int off, int len) It writes a portion of an array of characters. 4 void write(int c) It writes single character. 5 void write(String str) R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 42 It writes a string. 6 void write(String str, int off, int len) It writes a portion of a string. 7 Writer append(char c) It appends the specified character to the writer. 8 Writer append(CharSequence csq) It appends the specified character sequence to the writer 9 Writer append(CharSequence csq, int start, int end) It appends a subsequence of the specified character sequence to the writer. 10 void close() - It closes the output stream and also frees any resources connected with this output stream. Reading data using BufferedReader We can use the BufferedReader class to read data from the console. The BufferedInputStream class needs InputStreamReaderclass. The BufferedReader use a method read( ) to read a value from the console, or file, or socket. Let's look at an example code to illustrate reading data using BufferedReader. Example 1 - Reading from console import java.io.*; public class ReadingDemo { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); String name = ""; System.out.print("Please enter your name: "); name = in.readLine(); System.out.println("Hello, " + name + "!"); } } Example 2 - Reading from a file import java.io.*; public class ReadingDemo { public static void main(String[] args) throws IOException { Reader in = new FileReader(); try { char c = (char)input.read(); R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 43 System.out.println("Data read from a file - '" + c + "'"); } catch(Exception e) { System.out.println(e); } finally { input.close(); } } } Writing data using FileWriter We can use the FileWriter class to write data into the file. The FileWriter class use a method write( ) to write data. Example - Writing data into a file import java.io.*; public class WritingDemo { public static void main(String[] args) throws IOException { Writer out = new FileWriter("C:\\JNTU\\dataFile.txt"); String msg = "The sample data"; try { out.write(msg); System.out.println("Writing done!!!"); } catch(Exception e) { System.out.println(e); } finally { out.close(); } } } Console IO-Operations in Java R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 44 Reading console input in java In java, there are three ways to read console input. Using the 3 following ways, we can read input data from the console.  Using BufferedReader class  Using Scanner class  Using Console class Let's explore the each method to read data with example. 1. Reading console input using BufferedReader class in java Reading input data using the BufferedReader class is the traditional technique. This way of the reading method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the console. The BufferedReader class has defined in the java.io package. Consider the following example code to understand how to read console input using BufferedReader class. import java.io.*; public class ReadingDemo { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = ""; try { System.out.print("Please enter your name : "); name = in.readLine(); System.out.println("Hello, " + name + "!"); } catch(Exception e) { System.out.println(e); } finally { in.close(); } } } 2. Reading console input using Scanner class in java Reading input data using the Scanner class is the most commonly used method. This way of the reading method is used by wrapping the System.in (standard input stream) which is wrapped in a Scanner, we can read input from the console. The Scanner class has defined in R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 45 the java.util package. Consider the following example code to understand how to read console input using Scanner class. import java.util.Scanner; public class ReadingDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); String name = ""; System.out.print("Please enter your name : "); name = in.next(); System.out.println("Hello, " + name + "!"); } } 3. Reading console input using Console class in java Reading input data using the Console class is the most commonly used method. This class was introduced in Java 1.6 version. The Console class has defined in the java.io package. Consider the following example code to understand how to read console input using Console class. import java.io.*; public class ReadingDemo { public static void main(String[] args) { String name; Console con = System.console(); if(con != null) { name = con.readLine("Please enter your name : "); System.out.println("Hello, " + name + "!!"); } else { System.out.println("Console not available."); } } } Writing console output in java In java, there are two methods to write console output. Using the 2 following methods, we can write output data to the console.  Using print() and println() methods  Using write() method R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 46 Let's explore the each method to write data with example. 1. Writing console output using print() and println() methods The PrintStream is a bult-in class that provides two methods print() and println() to write console output. The print() and println() methods are the most widely used methods for console output. Both print() and println() methods are used with System.out stream. The print() method writes console output in the same line. This method can be used with console output only. The println() method writes console output in a separete line (new line). This method can be used with console ans also with other output sources. Let's look at the following code to illustrate print() and println() methods. public class WritingDemo { public static void main(String[] args) { int[] list = new int; for(int i = 0; i < 5; i++) list[i] = i*10; for(int i:list) System.out.print(i); //prints in same line System.out.println(""); for(int i:list) System.out.println(i); //Prints in separate lines } } 2. Writing console output using write() method Alternatively, the PrintStream class provides a method write() to write console output. The write() method take integer as argument, and writes its ASCII equalent character on to the console, it also acept escape sequences. Let's look at the following code to illustrate write() method. public class WritingDemo { public static void main(String[] args) { int[] list = new int; for(int i = 0; i < 26; i++) { list[i] = i + 65; } for(int i:list) { R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 47 System.out.write(i); System.out.write('\n'); } } } R22-OOPTJ-Unit2 Notes - Prepared by Dr. P. SAMMULAL, PROFESSOR, JNTUH Page 48

Use Quizgecko on...
Browser
Browser