Java Unit-2
Java Unit-2
The Java Compiler Show error when we declare a program like this to fulfill “Multiple
Inheritance”
class C extends A extends B // error
{
}
The above statement is invalid and Multiple Inheritnace is not possible in Java that is
classes in Java cannot have more than one Super Class.
But Java Provides alternate approach called “Interface”
Java Supports “Multiple Interfaces” to Support “Multiple Inheritance”
But it also needs a “Class”
Here interfaces are accessed by using keyword called “implements”
It also Supports “Hybrid Inheritance”
Syntax:
interface interfacename
{
Declaration of variables , Constants and methods
}
class classname implements interfacename
{
}
Ex: To achieve “Multiple Inheritance”
interface A
{
public void display1();//Declaration of Method only
}
interface B
{
public void display2();//Declartion of Method only
}
class C implements A,B// Here in Class "C" we use the properties of "A,B"
{
public void display1()
{
System.out.println("I am the Property of A");
}
public void display2()
{
System.out.println("I am the Property of B");
}
public void display3()
{
System.out.println("I am the Property of C");
}
}
class mul
{
public static void main(String args[])
{
C obj=new C();
obj.display1();
obj.display2();
obj.display3();
}
}
Extending Interfaces:
One interface is also extended by another interface
One Interface can inherit another by use of keyword “extends”
This is much like “inheriting class”
Ex:
interface one
{
void print1();
void print2();
}
interface two extends one
{
void print3();
}
class three implements two
{
public void print1()
{
System.out.println("I am One");
}
public void print2()
{
System.out.println("I am two");
}
public void print3()
{
System.out.println("I am three");
}
}
class test
{
public static void main(String args[])
{
three obj=new three();
obj.print1();
obj.print2();
obj.print3();
}
}
Q2) Explain about Method Overloading with Suitable Example
A)
Method overloading in Java is a programming concept when programmer declares two methods of
the same name but with different method signature, e.g. change in the argument list or change in
the type of argument.
Method overloading is a powerful Java programming technique to declare a method which
does a similar performance but with a different kind of input.
Example
One of the most popular examples of method overloading is System.out.println() method which is
overloaded to accept all kinds of data types in Java. You have println() method which takes String,
int, float,double or even char in output. All of those methods are collectively referred as an
overloaded method in Java.
Properties of method overloading in Java
1) Overloaded methods are bonded using static binding in Java. Which occurs during
compile time i.e. when you compile Java program. During the compilation process, compiler
bind method calls to the actual method.
2) Overloaded methods are fast because they are bonded during compile time and no
check or binding is required during runtime.
3) Most important rule of method overloading in Java is that two overloaded methods must
have a different signature.
If we need to do same kind of the operation with different ways i.e. for different inputs.
Different ways of doing overloading methods
In this approach the programmer use “Same method Name many times with same
datatype by changing the number of parameters”
class Addition{
Class student
{
public static void main (String[] args)
{
}
}
In the above example “add()” is a method we call it 2 times. At time of first call that is
“add(1,2)”, there are 2 parameters which are “integers”. In the same way another time
call “add(1,2,3)”. There are 3 parameters which are Integers. Both of them show the
“Addition of those arguments”.
class Addition{
class student {
public static void main (String[] args)
{
}
}
In the above example add() is a method where 3 Integers and 3 double values are passed with
same signature by using method Overloading
In this approach the programmer use “Same method Name, Same number of
Parameters but change the order of parameters”
class studentinfo{
class student {
public static void main (String[] args) {
obj.studentinfo("Hari",1);
obj.studentinfo(2,”Prasad”);
}
}
In the above example there are two method with same name “studentinfo()”. But in the sub
class programmer create first method as “String and Integer” whereas in Second Method as
“Integer and String”. Java Supports both of these issues. It Prints the result as follows
Output:
When the parent executes then the property of child hides and vice versa
Q4) Explain about Final in Java
In java final is a keyword or reserved word and can be applied to variables, methods, classes
etc.
The reason behind final keyword is to make entity non modifiable.
It means when you make a variable or class or method as final you are not allowed to change
that variable or class or method and compiler will verify this and gives compilation error if you
try to re-initialized final variables in java.
The final keyword in java is used to give restriction to the user. The java final keyword can be used
in many contexts. Final can be:
variable
method
class
Final Variable
Any variable which is declared by using the final keyword is called final variable.
Final variables can be declare in java and treated as constant.
A final variable can only be explicitly assigned once.
The below program shows how final variable value cannot be changed. It gives compilation
error if we want to change the value of final variable:
class FinalVariable1
{
public static void main(String args[])
{
final int i = 30;
i = 60;
}
}
Output:
Compiler Error: cannot assign a value to final variable i
Final method
Sometimes we may want to prevent a childclass to overriding a method from parentclass.
To do this we use final keyword with method declaration.
It means a method with final keyword is called final method.
Final methods are faster than non-final methods because they are not required to be resolved
during run-time and they are bonded on compile time.
The main reason behind making a method final would be that the content of the method
should not be changed by any outsider.
Program Example of Final Method:
Let us take an example to understand the use of final method.
Step 1: First we create a class X in which we declare the final method getMethod():
class X
{
final void getMethod()
{
System.out.println(“X method has been called”);
}
}
Step 2: Second we create a class Y which extends the class X and here we try to override the
method of above class:
class Y extends X
{
void getMethod() //cannot override
{
System.out.println(“Y method has been called”);
}
}
Step 3: Third we create a class FinalMethod in which we create an object of class Y:
class FinalMethod
{
public static void main(String[] args)
{
Y obj = new Y();
obj.getMethod();
}
}
Explanation:
On compiling the above program, it will display an compilation error “getMethod() in Y cannot
override getMethod() in X; overridden method is final.”
Final Class
A class with final keyword is known as final class in java. Final class is complete in nature
and cannot be inherited.
Several classes in Java are final e.g. String, Integer and other wrapper classes.
The main purpose or reason of using a final class is to prevent the class from being
subclassed.
If a class is marked as final then no class can inherit any feature from the final class.
Program Example of Final Class:
Let us take a program example to show the use of final class.
Step 1: First we create a class X and make it final class by using final keyword:
final class X
{
Void displayx()
{
System.out.println(“I am the Property of X”);
}
}
Step 2: Second we create a class Y which is trying to extend final class X:
class Y extends X
{
void displayy()
{
System.out.println(“I am the Property of Y”);
}
}
Step 3: Third we create a class FinalClass:
class FinalClass
{
public static void main(String args[])
{
Y obj=new Y();
obj.displayx();
obj.displayy();
}
}
Output:
Now it shows Compiler Error: cannot inherit from final X
Q5) Explain about Access Specifiers in Java
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
Ex:
classs student
{
public static void main(String args[])
{
String str=”good”;
System.out.println(str.toUpperCase());
}
}
In the above example the string “good” is Converted into “GOOD”.
toLowerCase():
It is a String method in Java. It is a Library or Built – in method in Java.
It is used to Convert any String into “LowerCase”. That means in “Small or Lower letters”.
It converters any case into “Lower Case” with the help of an String object
Syntax:
Stringobject.toLowerCase()
Ex:
String str=”GOOD”;
System.out.println(str.toLowerase());
In the above example the string “GOOD” is Converted into “good”.
length():
It is a String method in Java. It is a Library or Built – in method in Java.
Basically “length()” string method is used to findout the length of the given string.
It always return an “Integer value or Number”. This is also works with the help of String
object only.
Syntax:
Stringobject.length()
Ex:
class student
{
public static void main(String args[])
{
String str=”Good”;
int l;
l=str.length();
System.out.println(“Length of the String = “+l);
}
}
concat():
In Java “concat()” is a Built in String Method.
Here “concat” means “concatenation”. “Concatenation” means “combined or add”.
By using this method the programmer can combine two strings at a time. It always returns a
single string as a result.
In Java “+” is also used for “concatenation”. By using this also we can combine 2 or more
strings at a time.
Syntax:
String1.concat(string2)
Ex:
String str1=”Good”;
String str2=”Students”;
String str3=str1.concat(str2);
System.out.println(“After Concatination “+str3);
In the above 2 string str1,str2 are combined into str3 by using “concat()” method
shows the result “GoodStudents”
equals():
It is also a Built in String method in Java.
It is used to check two String objects at a time. Basically it is used to check a single
condition between 2 strings.
It always returns either “true” or “false”. But it shows results variation when Same Strings
are in different case.
That means “Uppercase or Lowercase”. This problem is avoided by using
“equalsIgnoreCase()” method.
Syntax:
Stringobject1.equlas(Stringobject2)
Ex:
class student
{
public static void main(String args[ ])
{
String str1=”java”;
String str2=”java”;
boolean res=str1.equals(str2);
System.out.println(“Result “+res);
}
}
In the above example it shows the result as “true”. Because str1 and str2 contains
same data.
substring():
It is a String Method in Java
It is used take a substring from the given string
That means it gather a small part from the original string
Syntax:
1. substring(int n)
2. substring (int m,int n)
Ex:
String str1=”abcdefgh”;
System.out.println(“Given String “+str1);
System.out.println(“Sub String from 3 to end “+str1.substring(3));
System.out.println(“Sub String from 0-3”+str1.substring(0,3));
charAt():
It is a String Method in Java which is Built in
It is used to find out “A particular Character at Particular Index Value”
It show the result based on “Index Value”
Syntax:
charAt(index i)
Ex:
String str1=”Java”
System.out.println(“The Character at 2 is “+str1.charAt(2));
Now it shows the “v”
indexOf():
It is a String Method in Java which is Built in
It is used to find out “A Index o f Particular a particular Character”
It show the result based on “given character”
Syntax:
indexOf(position)
indexOf(position,nth variable);
Ex:
String str1=”Java”
System.out.println(“The first index of ‘a’ is “+str1.indexOf(‘a’));
int i=str1.indexOf(‘a’);
System.out.println(“The next index of ‘a’ is “+str1.indexOf(‘a’,i+1));
replace():
It is a String Method in Java
It is used to “replaces every occurrences of one character with antother”
Syntax:
replace(existingcharacter,replacecharacter)
Ex:
String str1=”Java”;
System.out.println(“Replace j by k”+str1.replace(‘J’,’K’));
Now it shows the result “Kava”
trim():
It is a String method in Java
It is used to removing leading and trailing white spaces(blank) has been removed
Ex:
String str1=” test”;
System.out.println(str1.trim());
Now it removes the white spaces at beginning of the string
Syntax:
type methodname(parameterlist)
{
Method body;
}
Method Declaration have four basic parts:
i. The name of the method
ii. The type of the value the method returns
iii. A list of parameters
iv. The body of the method
Creating Objects
Real world entities are called as objects.
An object in java is essentially a block of memory that contains space to store all
the instance variables.
Creating an Object is also referred to as instantiating an object
Objects in java are created by using “new” operator.
JAVA always follows dynamic memory allocation but not static memory allocation.
In order to create a memory space in JAVA we must use an operator called new. This
new operator is known as dynamic memory allocation operator.
Logical runtime entity is known as an object.
For Example:
Pen is an Object. Its “name is Reynolds, Color is white etc., known as its
state”. It is used to Write , So Writing is the behavior of that object “Pen”
Syntax-1 for defining an OBJECT:
Ex:
student obj=new student()
Ex:
Student obj;
Obj=new Student()
Q8) Explain about Constructors in Java.
a)A constructor in Java is a special type of method that is used to initialize the object.
Constructor will be called automatically when the object is created.
Constructor name must be similar to name of the class.
Constructor should not return any value even void also. Because basic aim is to place the
value in the object. (if we write the return type for the constructor then that constructor will
be treated as ordinary method).
Constructor definitions should not be static. Because constructors will be called each and
every time, whenever an object is creating.
It is basically used to initialize values for the object
In “Java” Constructors are basically divided into 3 types. They are
1. No argument Constructor
2. Argument Constructor
3. Copy Constructor
No Argument Constructor:-
A Constructor that has no Parameter or argument is called “No Argument Constructor”.
When we create an object “we does not pass any values from the object”
It is also used to initialize values for the object
It is Automatically called when we creates the object of class
In this Constructor the programmer must remember name of Constructor is same as name
of class
No argument Constructor never declared with the help of Return Type. Means cant Declare
a Constructor with the help of “void Return Type. “
It is called by the JVM automatically itself whenever the programmer creates an “Object”.
Syntax:
Classname()
{
Initialize values
}
Ex:
Class addition
{
int a,b;
addition()
{
a=10;
b=20;
}
void display()
{
System.out.println(“Result “+(a+b));
}
}
Class student
{
Public static void main(String args[])
{
addition obj=new addition();
obj.display();
}
}
In the above example “addition” is class. When we create object “obj” then the
“JVM” automatically calls and initializes values in the constructor “addition()”. This constructor
does not contain any values at the time of object creation because of this reason it is called
“No argument Constructor”.
Argument Constructor:-
A Constructor that has Parameter or argument is called “Argument Constructor”.
When we create an object “we pass values or arguments from the object”
It is also used to initialize values for the object
It is Automatically called when we creates the object of for class
In this Constructor the programmer must remember name of Constructor is same as name
of class
Argument Constructor never declared with the help of Return Type. Means cant Declare a
Constructor with the help of “void Return Type. “
It is called by the JVM automatically itself whenever the programmer creates an “Object”.
Syntax:
Classname(parameterlist)
{
Initialize values
}
Ex:
Class addition
{
int a,b;
addition(int x,int y)
{
a=x;
b=y;
}
void display()
{
System.out.println(“Result “+(a+b));
}
}
Class student
{
Public static void main(String args[])
{
addition obj=new addition(10,20);
obj.display();
}
}
In the above example “addition” is class. When we create object “obj” then the
“JVM” automatically calls and initializes values in the constructor “addition(10,20)”. This
constructor pass values 10,20 to the constructor in the addition class. Here we pass
parameters from the object that’s why it is called “Argument Constructor”.
Copy Constructor:-
A Constructor that copies values from another object is called “Copy Constructor”
It Copies the values from either “No arugment Constructor” or “ Argument Constructor”
Some times it copies values from both of them
Here we pass “Object” as a Paramter
It is also used to initialize values for the object
It is Automatically called when we creates the object of class
In this Constructor the programmer must remember name of Constructor is same as name
of class
Copy Constructor never declared with the help of Return Type. Means cant Declare a
Constructor with the help of “void Return Type. “
It is called by the JVM automatically itself whenever the programmer creates an “Object”.
Syntax:
Classname(classname Object)
{
Initialize values
}
Ex:
Class addition
{
int a,b;
void display()
{
System.out.println(“Result “+(a+b));
}
}
Class student
{
Public static void main(String args[])
{
addition obj1=new addition(10,20);//parameterized constructor
addition obj2=new addition(obj1);//copy constructor
obj1.display();
obj2.display();
}
}
In the above example “addition” is class. When we create object “obj1” then the
“JVM” automatically calls and initializes values in the constructor “addition(10,20)”. There after those
values are copied by another object “obj2” with the help of “copy Constructor” that is declared at
“class addition”.
There is no destructor in “Java”. Because “Java” has a feature called “Automatic Garbage
Collection”.
Some times the programmer calls “protected void finalize()” for the sake of garbage issue.
Ex:
this.a=a
this.display()
this(10,20)
Example:
class A
{
void display()
{
System.out.println(“I am the Property of A”);
}
}
Class B extends A
{
Void display( )
{
super.display();
System.out.println(“I am the Propety of B”);
}
}
class superexample
{
public static void main(String args[ ] )
{
B objb=new B( );
objb.display();
}
}
Abstract Method:
A method that doesn't have its body is known as an abstract method. We use
the same abstract keyword to create abstract methods
Syntax:
abstract class classname
{
Variables ;
abstract returntype methodname( );
returntype normalmethodname( )
{
Coding
}
}
Example:
In Java, the following some important observations about abstract classes are as follows:
1. An instance of an abstract class can not be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Ex:
Integer.parseInt(args[0]);
Float.parseFloat(args[1])
Ex:
class a
{
public void display()
{
System.out.println("I am Parent");
}
}
class b extends a
{
public void display1()
{
System.out.println("I am Child");
}
}
class single
{
public static void main(String args[])
{
b obj=new b();
obj.display();
obj.display1();
}
}
In the above example the subclass 'b' use both the properties of 'b' (subclass) and
'a'(superclass) also
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class. In below image, the
class A serves as a base class for the derived class B, which in turn serves as a base class for the
derived class C. In Java, a class cannot directly access the grandparent’s members.
class a
{
public void display1()
{
System.out.println("I am Property of 'a-Super class'");
}
}
class b extends a
{
public void display2()
{
System.out.println("I am Property of b-Subclass");
}
}
class c extends b
{
public void display3()
{
System.out.println("I am Property of c-subclass");
}
}
class multilevel
{
public static void main(String args[])
{
b obj1=new b();
c obj2=new c();
Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more than
one superclass and inherit features from all parent classes. Please note that Java
does not support multiple inheritance with classes. In java, we can achieve multiple inheritance only
through Interfaces. In image below, Class C is derived from interface A and B.