Strings in Java | ||
StringBuffer & StringBuilder | ||
OOPS in Java | ←Back Week One Tutorial | Goto Week Three Tutorial→ |
Classes & Objects | ||
Methods in Java | ||
Inheritance in Java |
Strings in Java
A group of characters are called 'Strings'. For example, in a bank, there are credit card numbers, names, and addresses etc. which all are strings. String is an object of String class from the java.lang package.
There are three ways to create strings in Java Programming:
We can assign a group of characters to a string type variable. Here JVM creates an object and stores string "David" into that object.
String concat(String s) int length(); char charAt(int i) boolean equals(String s) int indexOf(String s)Let us have a code snippet which covers few of the above method including how to create strings.
We have been able to create two string objects, measure the length of characters and we were able to concatenate two strings in one line in the example above. Result of the above code will look like this:
StringBuffer and StringBuilder in Java
StringBuffer class is used to represent character that can be modified. It means StringBuffer class objects are mutable unlike Strings that we studied in previous chapter. Mostly StringBuffer is used for concatenation or manipulation of the strings. A StringBuffer implements the mutable sequence of the characters. We can create StringBuffer objects in two ways.
StirngBuffer strb = new StringBuffer("My Java");and By allotting memory to the StringBuffer object using 'new' operator and later storing it into it such as: StirngBuffer strb = new StringBuffer();Here we are creating a StringBuffer empty object but not passing any string to it. StringBuffer will be created with 16 characters with default values. StringBuffer strb = new StringBuffer(30); What above code explains is that StringBuffer is created with 30 characters capacity. Now, is it possible to store more than 30 characters? Yes because StringBuffer has mutability feature, it can be modified. We can use append(), or insert() method to do it. Let us have a code snippet to reflect preceding chapters.
We have tried to append first name and last name and we were able to print out the results displaying first and last name in the monitor. Then, we realized that we'd missed the middle name. How do we append middle name, then? By using insert() method, we can append middle name as in above example code.
StringBuilder Class. StringBuilder strb = new StringBuilder ("David"); StringBuilder strb = new StringBuilder (); StringBuilder strb = new StringBuilder (30); Only difference between these two classes are StringBuffer is synchronized by default while StringBuilder is not.
Programmers have firmly followed Procedural oriented approach for several decades and there is sudden shift in the software industry for new approach, called OOPs (Object Oriented Programming). Fortran, Pascal, C etc. languages were procedural because these language use procedural or functions to perform a task. Languages like C++, Java are called Object Oriented Programming. In procedural method, programmers write set of functions to achieve one task, and whenever he wants to perform new task, then he would be writing a new set functions hence there will be no reusability. If programmers can write the new modules with the help existing old modules, that would be more easy and quick. Due to these reason, a new approach of object oriented programming emerged in the computer software market. Features of Object Oriented Programming
Class & Object in Java String name Char sex; int age; So, above properties can be similar to other objects such as Mohan who have the same characters (properties) as David. Now what we can think of is they both fall into one class called 'Person' and share the same properties. Now we can say person do not exists but David and Mohan do exist. Another example can be an Animal class and a dog, a tiger, a lion all objects from class Animal. Let us draw a code snippet for creating a class called 'Animal'.
Now a class model has been built with two variables (name, size) and two methods eat(), sleep(). Let us create an object out of above class Animal. Animal Dave = new Animal();
Encapsulation in Java: We will declare variables as 'private'. 'private' is called access specifier which makes the members of a class not to be accessible outside the Animal Class. To access these variables we use methods which generally declared as public. Let us have a code snippet which reflects encapsulation in java. Here we build a class 'Animal' and declare its variable as private.
Only talk() method can access to those private variables and by calling talk() method using Animal class object, we can make Animal talk for us.
Abstraction in Java
In the above code snippet we have been able to abstract unnecessary data and made it available only necessary data to an accountant. Obviously he can not access to bank's annual profit and loss data.
Inheritance in Java
We can derive all the qualities of the members of class A to members of class B as well as we are able to define new variable for class B. Java keyword 'extends' is used to inherit Class A's characteristics to Class B. if we create an object from class B, it inherits all the members of Class A as well as of class B. Inheritance is a significant feature of java programming as it makes easy to manage code, conveniently we can create another class from existing class.
Polymorphism in Java
In Polymorphism, a single variable can be used with different objects of related classes. We can use variable with dot (.) notation with the method() to invoke the method. Such as: variable.method()mentioned in the above example. We discussed about classes and object little bit in previous chapter. Now we will discuss more about them. An object is the instance of the class as an object is created/instantiated from a class. That is why class is called a model for objects. All the variables and methods created in the class can be inherited to the instance of the class.
We observe above that java keyword 'class' is used to create a class following with the class name. We declare instance variable and methods for the class. Since the method has void java keyword, it means no result is returned and it does not take any data from us also. Now we will create an object out of the above class. Animal animal1 = new Animal(); Animal is the class and animal1 is object name. so 'animal1' is reference of Animal object. 'new' operator is used to create object. When object is created, it is stored in 'Heap' memory. Once object is stored, JVM creates a unique reference number called hash code numberfor the object (animal1) below. Let us create a class 'Animal' and an object 'Lion' to an Animal class. and we will make it hash code display as well.
Output of the above code snippet would be as follows: Animal has: null (we got null value because we did not initialize instance variables) Animal has:0 (we got null value because we did not initialize instance variables ) Hash Code is: 25669322
Using reference variables, we can refer to the instance variables and methods such as: animal1.name; animal1.talk(); How to Initialize Instance variables in Java
Access Specifiers
As we clearly see that we did not initialize Animal class with 'private keyword', as a result DemoSpecifier class can access these instance variables and overwrite the value. To protect from overwriting or accessing data from outsider, we use java keyword 'private'. Here is how we can declare instance variables by using 'private' key. private String name = "Lion"; private in size = 150; Access Specifier is the keyword that specifies how to access to the variables and methods of the class. There are four types of access specifiers in Java. public: public access specifier cab be used from inside and outside of the class. private: private access specifier is only accessible within same class by the methods but not accessible from outside the class from other programs. protected: protected members of a class is accessible from inside and outside of the class but only within the same directory. default: If no access specifier is defined, then Java will provide a default specifier which is accessible inside and outside of the class but within the same directory.
Constructor: Constructor is like method in java which is used to initialize instance variables. This is third possible ways of initializing instance variables. The only goal of constructor is to initialize instance variables. Constructor's name should be similar to Class's name Constructor's name should end with opening & closing bracessuch as: Animal( ) { }Constructor may have variables in it which is called constructor's parameters. Constructor's parameters are used to receive data from outside into the constructor. Constructor does not return value and do not use 'void'. During the creation of object, if nothing is passed to the object, the default constructor is called executed. If some values are passed to the object, then parameterized constructor is called. A Constructor is called once per object. Such as if an object is created, and constructor is called. If we create second constructor, again constructor is called. Constructor is called concurrently when an object is created. Here is a simple code snippet for constructor. Animal(String s, int k) { } Animal tiger = new Animal();//default constructor is called Animal tiger = new Animal("Tiger", 150);//Parameterized constructor will receive "Tiger" and size =150
Let us have code snippet with constructor.
Output would be: It is a :Tiger It weighs :150 It is a :Tiger It weighs :150 As we noticed above that both the objects tiger and lion have same output Tiger and 150 respectively. We will resolve this problem by using parameterized constructor which takes data from outside and initialize instance variables with that data.
Output would be: It is a :Tiger It weighs :150 It is a :Lion It weighs :180
So, what we understand from above code that we have parameterized constructor String s; and int k; and these parameter receive data from outside as from DemoAnimal class such as: Animal lion = new Animal("Lion", 180);. Now 'Lion' is copied into parameter s, and 180 pound is copied to parameter k and from there, these values are copied to original instance variables: name, and size. If we do not pass any values while creating a new object, then default constructor is called which is: Animal tiger = new Animal();
Method performs an action in Java which is a set of statements. Action is i.e. calculation, processing data etc. Method name begins with lower case i.e. sqrt() method which calculates square root value. Method contains method name, parameters, method return data type, and method body. This should look as follows. returndatatype methodName(parm1, parm2,…) int sqrt(int num)When Return data type is 'void', it does not return any value and do not accept data from outside and void method comes with the pair of empty braces '()'and method never returns more than one value such as: return x, y;is invalid statement void methodName()Method body looks as follows: { Statements; } { int i=a+b; System.out.println("Total sum is:" +i); }If we want to return value then we will have statement look as follows: { int i = a+b; return i; }Let us create a code snippet that explains methods in detail.
In the above example, sum() method returns the total sum and store the sum into x. and above method is called instance method as it is acting on the instance variables. Method that is not acting on the instance variables is called static method and can not access to instance variable but if variable is declared as 'static', then static method can access to static variables. Static variable is also called 'class variable' and static method is also called 'class method'. Similarly, local variable or parameters declared inside the method can not be accessed outside the methods such as: //instance variable private int x; void testMethod(int x): { x=x; }In the above code, the local variable is x and only accessible within methods. Now notice that we can see above that the instance variable and local variable are conflicting as both of them are holding the same variable. How do we deal in this kind of situation? Java keyword 'this'is used to handle this problem. 'this' keyword refers to the object of the classes where it has been used. Members of the class, instance variable, constructors, methods are referenced by 'this'.
OUTPUT will be: Sum is: 10 An object 'T' is created. Default constructor Test is executed passing value 10 to the instance variable x. Hence, present class's this.x=x; instance variable is initialized and executed giving the result = 10.
Setter & Getter Methods objectName.methodName()and they can access instance variable as well as static variables. There are two types of Instance methods: a) Getter or Accessor Method b) Setter or Mutator Method Getter or Accessor Method can only access or read instance variable whereas Setter or Mutator method can access and modify instance variable. Let us write a code snippet to reflect setter and getter methods
OUTPUT will be: Name: David Gender: M
How to pass primitive data to Methods?
OUTPUT will be: Sum is: 12
How to pass objects to Methods? Person theMethod(Person obj1) { statements; return obj1; }Here theMethod() takes Person class object and Person class is declared in parameter of the method and method returns obj1. Similarly we can pass an array to methods and return arrays from the methods. Let us see how it works: String[] myMethod(String arr[ ])In the above code snippet, single dimensional array of String type 'arr' is passed to method 'myMethod. What is Inheritance in Java? Inheritance simply means to inherit the characteristics from the original class. New classes/objects can be created by inheriting few or all the members of the original class allowing the newly created class to perform exactly what the base class can perform. So Inheritance relationship is considered as transitive. 'extends' java keyword or clause is used to inherit characteristics from base class or super class to subclass or derived class.
Super class members are always available for subclass because subclass contains a copy of super class. So the advantage of Inheritance is saving lot of space and easy to develop hence allowing to grow the productivity and efficiency. Programmer can reuse the super class's characteristics without rewriting the whole code. Java keyword 'super' is used to access to super class. If we create an object to super class, we will only be able to access super class members but not be able to access subclass object. In contrary, if an object is created to subclass, both super class members and subclass members can access to it. Super can be used to refer to super class variables as super.variable, super class method as super.method(), and super class constructor as super(values)
what is 'Protected Specifier'? When private members of the super class are restricted to sub classes. When we want to access private super class member from subclass, we can use java keyword 'protected'(specifier). So protected is used in the super class to make members available directly to its sub classes.
There are two types of Inheritance:Single and Multiple Inheritance. Simply put, one super class and many sub classes is single Inheritance where as multiple super classes and one or more sub classes is Multiple Inheritance. The concept of Multiple Inheritance is true with C++ but in Java, no more Multiple Inheritance is accepted or allowed. Multiple Inheritance creates confusions amongst programmers. To accommodate Multiple Inheritance, programmers prefer using Interface such as: Class TestClass implements interfaceOne, interfaceTwo,…Now, TestClass can have all the members of interfaceOne, and interfaceTwo inherited to it. |
No comments:
Post a Comment