🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

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

Document Details

ThinnerRainbow

Uploaded by ThinnerRainbow

Ama International University

Tags

object-oriented programming Java programming concepts

Full Transcript

Object Oriented Programming OOP Concepts MODULE 2 - Object Oriented Programming Concepts This module will guide you on what is a class and how does Java deal with objects. You will know how to create a class and instantiate...

Object Oriented Programming OOP Concepts MODULE 2 - Object Oriented Programming Concepts This module will guide you on what is a class and how does Java deal with objects. You will know how to create a class and instantiate its object. These are the basic building blocks of object-oriented programming (OOP) in Java. At the end of this module, the student should be able to: 1. Identify classes and objects in java 2. Understand the concept of encapsulation in java 3. Write constructors in java program 4. Define packages used in java Object-Oriented Programming Many time you must have come across the phrase Java is an Object-Oriented Programming Language. The term Object-Oriented denotes a concept in software development. It is a way of organizing software in the form of objects that contain both data and the behavior of these objects. Therefore, Object-Oriented Programming Languages, generally known as OOP, provide the programming model for simplifying for software development, design and maintenance under some well-established ground rules. The projects made in OOPS are more structured towards objects. As a result, it increases performance, maintainability, and development of the program. The main idea behind OOP is to incorporate data and behavior under the same location(objects). Class in Java A class in Java or any other Object-oriented Language is a blueprint for objects to follow a specific schema defined in the class. Classes define the behavior for objects of its type. It represents a collection of properties (data and functions) for all its objects. It supports a template for creating objects which bind code and data. Further, classes act as a means to define methods and data. It helps in maintaining access specifications for member variables using access specifiers. Object in Java An Object is the most fundamental entity in Java or any other Object-Oriented Language. Objects represent real-life entities because each of them could have specific behavior, identity, and data (attributes). In Java, the object is an offspring of its class. The class has properties to reflect the object state and methods to represent the behavior. The methods also show an object’s response to other objects. Identity is a unique name for the object assigned by the user, much like variables. 1|P age Object Oriented Programming OOP Concepts Let’s have a profound look into what are objects. If we think about this present reality, we can discover numerous articles around us, vehicles, people, and so on. Every one of these has a unique state and behavior. You can’t expect a human being to bark like a dog or a dog to speak like a human. For example – A car, its state are – name, model no, shade, manufacturer and its behavior can be – moving, blinking the headlights, honking, etc. If you try to compare a Java object with any real-time entity, they could probably have fundamentally same attributes. public class Car { // Class Attributes – State of an object String color; Int model_no; String name; String manf; // Class Methods – Behavior of an object void brake(){ } void accelerate(){ } void turn(){ } } A class can have any number of functions to access the properties of the class’s object or manipulate the properties. In the above example, move(), blink() and honk() are a few methods. Variable Types: A class can contain any of the accompanying variable sorts: Class Variables: A class variable is one which has the static keyword as a prefix in its declaration. Its definition occurs only inside a class and outside any function. Local Variables: These are variables which have declarations inside methods, constructors or blocks. They are local to the part of the code they belong. Local variables come into existence when the control enters into the code block that keeps their declaration. And they vanish with the block leaving out of execution. Instance Variables: These variables are inside a class however outside any method. They come into existence when the class instantiates. These are accessible from any constructor or block of that specific class. 2|P age Object Oriented Programming OOP Concepts Access Modifiers Java supports four access modifiers that you can use to define the visibility of classes, methods, and attributes. Each of them specifies a different level of accessibility, and you can only use one modifier per class, method or attribute. As a rule of thumb, you should always use the most restrictive modifier that still allows you to implement your business logic. These modifiers are, starting from the most to the least restrictive one:  private  no modifier  protected  public Let’s take a closer look at each of these modifiers and discuss when you should use them. Private This is the most restrictive and most commonly used access modifier. If you use the private modifier with an attribute or method, it can only be accessed within the same class. Subclasses or any other classes within the same or a different package can’t access this attribute or method. As a rule of thumb, the private modifier should be your default choice for all attributes and internal methods that shouldn’t be called from external classes. You might need to make an exception to this rule when you’re using inheritance, and some of the subclasses need direct access to an attribute or internal method. In that case, you should use the protected modifier instead of private. No modifier When you don’t provide any access modifier for your attribute or method, you can access it within your class and from all classes within the same package. That’s why it’s often called package-private. Protected Attributes and methods with the access modifier protected can be accessed within your class, by all classes within the same package, and by all subclasses within the same or other packages. The protected modifier gets mostly used for internal methods that need to be called or overridden by subclasses. You can also use it to allow subclasses to access internal attributes of a superclass directly. Public This is the least restrictive access modifier. Methods and attributes that use the public modifier can be accessed within your current class and by all other classes. Public methods and attributes become part of the public API of your class and of any component in which you include them. That is almost never a good idea for any attribute, and you should think twice before you use this modifier on a method. 3|P age Object Oriented Programming OOP Concepts If a method is publicly available, you need to make sure that it’s well documented and that it robustly handles any input values. Also keep in mind, that sooner or later this method will be used by some part of your application that will make it hard to change or remove it. Here you can see an overview of the different access modifiers and the accessibility of the attributes or methods. Encapsulation simply means binding object state(fields) and behaviour(methods) together. If you are creating class, you are doing encapsulation. In this guide we will see how to do encapsulation in java program, if you are looking for a real-life example of encapsulation then refer this guide: OOPs features explained using real-life examples. What is encapsulation? The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update (for example void setSSN(int ssn))and read (for example int getSSN()) the private data fields then the outside class can access those private data fields via public methods. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better. Example of Encapsulation in Java How to implement encapsulation in java: 1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class. 2) Have getter and setter methods in the class to set and get the values of the fields. 4|P age Object Oriented Programming OOP Concepts class EncapsulationDemo{ private int ssn; private String empName; private int empAge; //Getter and Setter methods public int getEmpSSN(){ return ssn; } public String getEmpName(){ return empName; } public int getEmpAge(){ return empAge; } public void setEmpAge(int newValue){ empAge = newValue; } public void setEmpName(String newValue){ empName = newValue; } public void setEmpSSN(int newValue){ ssn = newValue; } } public class EncapsTest{ public static void main(String args[]){ EncapsulationDemo obj = new EncapsulationDemo(); obj.setEmpName("Mario"); obj.setEmpAge(32); obj.setEmpSSN(112233); System.out.println("Employee Name: " + obj.getEmpName()); System.out.println("Employee SSN: " + obj.getEmpSSN()); System.out.println("Employee Age: " + obj.getEmpAge()); } } Output: Employee Name: Mario Employee SSN: 112233 Employee Age: 32 In above example all the three data members (or data fields) are private(see: Access Modifiers in Java) which cannot be accessed directly. These fields can be accessed via public methods only. Fields empName, ssn and empAge are made hidden data fields using encapsulation technique of OOPs. Advantages of encapsulation 1. It improves maintainability and flexibility and re-usability: for e.g. In the above code the implementation code of void setEmpName(String name) and String getEmpName() can be changed at any point of time. Since the implementation is purely hidden for outside classes 5|P age Object Oriented Programming OOP Concepts they would still be accessing the private field empName using the same methods (setEmpName(String name) and getEmpName()). Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class. 2. The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) that we don’t want to be changed so we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field. 3. User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them. Encapsulation is also known as “data Hiding“. What is a Constructor? Constructor looks like a method but it is in fact not a method. It’s name is same as class name and it does not return any value. You must have seen this statement in almost all the programs I have shared above: MyClass obj = new MyClass(); If you look at the right side of this statement, we are calling the default constructor of class myClass to create a new object (or instance). We can also have parameters in the constructor, such constructors are known as parametrized constructors. Example of constructor public class ConstructorExample { int age; String name; //Default constructor ConstructorExample(){ this.name="Chaitanya"; this.age=30; } //Parameterized constructor ConstructorExample(String n,int a){ this.name=n; this.age=a; } public static void main(String args[]){ ConstructorExample obj1 = new ConstructorExample(); ConstructorExample obj2 = new ConstructorExample("Steve", 56); System.out.println(obj1.name+" "+obj1.age); System.out.println(obj2.name+" "+obj2.age); } } 6|P age Object Oriented Programming OOP Concepts A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java we use packages to organize our classes and interfaces. We have two types of packages in Java: built-in packages and the packages we can create (also known as user defined package). In this guide we will learn what are packages, what are user-defined packages in java and how to use them. In java we have several built-in packages, for example when we need user input, we import a package like this: import java.util.Scanner Here: → java is a top level package → util is a sub package → and Scanner is a class which is present in the sub package util. Before we see how to create a user-defined package in java, lets see the advantages of using a package. Advantages of using a package in Java These are the reasons why you should use packages in Java:  Reusability: While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, you can create such things in form of classes inside a package and whenever you need to perform that same task, just import that package and use the class.  Better Organization: Again, in large java projects where we have several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.  Name Conflicts: We can define two classes with the same name in different packages so to avoid name collision, we can use packages Types of packages in Java As mentioned in the beginning of this guide that we have two types of packages in java. 1) User defined package: The package we create is called user-defined package. 2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages. We have already discussed built-in packages, lets discuss user-defined packages with the help of examples. Example 1: Java packages I have created a class Calculator inside a package name letmecalculate. To create a class inside a package, declare the package name in the first statement in your program. A class can have only one package declaration. Calculator.java file created inside a package letmecalculate 7|P age Object Oriented Programming OOP Concepts package letmecalculate; public class Calculator { public int add(int a, int b){ return a+b; } public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(10, 20)); } } Now lets see how to use this package in another program. import letmecalculate.Calculator; public class Demo{ public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(100, 200)); } } To use the class Calculator, I have imported the package letmecalculate. In the above program I have imported the package as letmecalculate.Calculator, this only imports the Calculator class. However if you have several classes inside package letmecalculate then you can import the package like this, to use all the classes of this package. import letmecalculate.*; Example 2: Creating a class inside package while importing another package As we have seen that both package declaration and package import should be the first statement in your java program. Lets see what should be the order when we are creating a class inside a package while importing another package. //Declaring a package package anotherpackage; //importing a package import letmecalculate.Calculator; public class Example{ public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(100, 200)); } } So the order in this case should be: → package declaration → package import Example 3: Using fully qualified name while importing a class You can use fully qualified name to avoid the import statement. Lets see an example to understand this: Calculator.java package letmecalculate; 8|P age Object Oriented Programming OOP Concepts public class Calculator { public int add(int a, int b){ return a+b; } public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(10, 20)); } } Example.java //Declaring a package package anotherpackage; public class Example{ public static void main(String args[]){ //Using fully qualified name instead of import letmecalculate.Calculator obj = new letmecalculate.Calculator(); System.out.println(obj.add(100, 200)); } } In the Example class, instead of importing the package, I have used the full qualified name such as package_name.class_name to create the object of it. You may also want to read: static import in Java Sub packages in Java A package inside another package is known as sub package. For example If I create a package inside letmecalculate package then that will be called sub package. Lets say I have created another package inside letmecalculate and the sub package name is multiply. So if I create a class in this subpackage it should have this package declaration in the beginning: package letmecalculate.multiply; Multiplication.java package letmecalculate.multiply; public class Multiplication { int product(int a, int b){ return a*b; } } Now if I need to use this Multiplication class I have to either import the package like this: import letmecalculate.multiply; or I can use fully qualified name like this: letmecalculate.multiply.Multiplication obj = new letmecalculate.multiply.Multiplication(); 9|P age Object Oriented Programming OOP Concepts Points to remember: 1. Sometimes class name conflict may occur. For example: Lets say we have two packages abcpackage and xyzpackage and both the packages have a class with the same name, let it be JavaExample.java. Now suppose a class import both these packages like this: import abcpackage.*; import xyzpackage.*; This will throw compilation error. To avoid such errors you need to use the fully qualified name method that I have shown above. For example abcpackage.JavaExample obj = new abcpackage.JavaExample(); xyzpackage.JavaExample obj2 = new xyzpackage.JavaExample(); This way you can avoid the import package statements and avoid that name conflict error. 2. I have already discussed this above, let me mention it again here. If we create a class inside a package while importing another package then the package declaration should be the first statement, followed by package import. For example: package abcpackage; import xyzpackage.*; 3. A class can have only one package declaration but it can have more than one package import statements. For example: package abcpackage; //This should be one import xyzpackage; import anotherpackage; import anything; 4. The wild card import like package.* should be used carefully when working with subpackages. For example: Lets say: we have a package abc and inside that package we have another package foo, now foo is a subpackage. classes inside abc are: Example1, Example 2, Example 3 classes inside foo are: Demo1, Demo2 So if I import the package abc using wildcard like this: import abc.*; Then it will only import classes Example1, Example2 and Example3 but it will not import the classes of sub package. To import the classes of subpackage you need to import like this: import abc.foo.*; This will import Demo1 and Demo2 but it will not import the Example1, Example2 and Example3. So to import all the classes present in package and subpackage, we need to use two import statements like this: 10 | P a g e Object Oriented Programming OOP Concepts import abc.*; import abc.foo.*; Sources Agarwal, M. (n.d.). Class and Object in Java - OOPs. https://www.techbeamers.com/java-class-object/ Janssen, T. (2017). OOP Concept for Beginners: What is Encapsulation https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/ Singh, C. (2013). Encapsulation in java with example. https://beginnersbook.com/2013/05/encapsulation-in-java/ 11 | P a g e

Use Quizgecko on...
Browser
Browser