KEMBAR78
Java Unit-2 | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
12 views25 pages

Java Unit-2

This document provides an overview of key Java programming concepts including interfaces, method overloading, method overriding, the final keyword, access specifiers, and string manipulation. It explains how interfaces facilitate multiple inheritance, the rules and examples of method overloading and overriding, the use of the final keyword to restrict modifications, and the four types of access modifiers in Java. Additionally, it discusses string methods and their functionalities, emphasizing the immutability of string objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views25 pages

Java Unit-2

This document provides an overview of key Java programming concepts including interfaces, method overloading, method overriding, the final keyword, access specifiers, and string manipulation. It explains how interfaces facilitate multiple inheritance, the rules and examples of method overloading and overriding, the use of the final keyword to restrict modifications, and the four types of access modifiers in Java. Additionally, it discusses string methods and their functionalities, emphasizing the immutability of string objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT-2

Q1) Explain about Interfaces in Java


A.
 Interface is a collection of methods declaration and constants that one or more classes
of object will use
 Interface is a also a class it does not contain any declaration part
 Java does not support the Concept of “Multiple Inheritance” Directly
 With the help of Interfaces we can handle “Multiple Inheritance”
 Basically Multiple Inheritance means that enables you to derive a subclass from more
then one parent class
 For example A and B are Superclasses we derive class C from both

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.

Need of method Overloading

 If we need to do same kind of the operation with different ways i.e. for different inputs.
Different ways of doing overloading methods

Method overloading can be done by changing:


 The number of parameters in two methods.
 The data types of the parameters of methods.
 The Order of the parameters of methods.

The number of Parameters in two Methods:

In this approach the programmer use “Same method Name many times with same
datatype by changing the number of parameters”

Method 1: By changing the number of parameters.

class Addition{

// adding two integer values.


int add(int a, int b)
{

int sum = a+b;


return sum;
}

// adding three integer values.


int add(int a, int b, int c)
{

int sum = a+b+c;


return sum;
}

Class student
{
public static void main (String[] args)
{

Addition obj= new Addition();

int sum1 = ob.add(1,2);

System.out.println("sum of the two integer value :" + sum1);

int sum2 = ob.add(1,2,3);

System.out.println("sum of the three integer value :" + sum2);

}
}

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”.

The data types of the parameters of methods.


In this approach the programmer use “Same method Name, Same number of
Parameters with different datatypes “

Method 2: By changing the Data types of the parameters

class Addition{

// adding three integer values.


public int add(int a, int b, int c){

int sum = a+b+c;


return sum;
}

// adding three double values.


public double add(double a, double b, double c){

double sum = a+b+c;


return sum;
}
}

class student {
public static void main (String[] args)
{

Addition ob = new Addition();


int sum2 = ob.add(1,2,3);
System.out.println("sum of the three integer value :" + sum2);
double sum3 = ob.add(1.0,2.0,3.0);
System.out.println("sum of the three double value :" + sum3);

}
}
In the above example add() is a method where 3 Integers and 3 double values are passed with
same signature by using method Overloading

The Order of the parameters of methods.

In this approach the programmer use “Same method Name, Same number of
Parameters but change the order of parameters”

Method 3: By changing the Order of the parameters

class studentinfo{

public void studentinfo(String name, int id){

System.out.println("Student Name :"+ name +" "+"Student Id :"+ id);


}

public void studentinfo(int id, String name){

System.out.println("Student Id :"+ id +" "+"Student Name :"+ name);


}
}

class student {
public static void main (String[] args) {

studentinfo obj=new studentinfo()

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:

Name : Hari Student Id: 1


Student Id : 2 Name : Prasad
Q3) Explain about Method Overriding in Java
A)
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Ex:
class parent
{
public void display()
{
System.out.println(“I am Parent”);
}
}
class child extends parent
{
public void display()
{
System.out.println(“I am Child”);
}
}
Class sksd
{
Public static void main(String args[ ])
{
parent obj1=new parent();
child obj2=new child();
obj1.display()
obj2.display()
}
}

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.

Q6 )Explain about Strings in “Java”. Explain any 5 methods in “Java”.


A)
 In Java it is very important concept. Basically “String” means “Collection of Characters”.
 Some other language like “C and C++” supports it by using “Character Array”
 In Java String is probably the most commonly used class in java library.
 String class is encapsulated under java.lang package.
 In java, every string that programmer creates is actually an “object of type String”.
 One important thing to notice about string object is that “string objects” are “immutable “
 An object whose state cannot be changed after it is created is known as an “Immutable”
object.
 String, Integer, Byte, Short, Float, Double and all other wrapper classes objects” are
immutable.
 When ever the programmer creates a “string object” then it stored or referred at “HEAP
MEMORY”
In “Java” there are various types of “String Methods “ in Java.
 toUpperCase()
 toLowerCase()
 length()
 concat()
 equals()
 equalsIgnoreCase()
 substring()
 chartAt()
 indexOf()
 replace()
toUpperCase():
 It is a String method in Java. It is Built – in method in Java.
 It is used to Convert any String into “UpperCase”. That means in “Capital” letters.
 It Converts any case into “Upper Case” with the help of String object
Syntax:
Stringobject.toUpperCase()

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));

Now it shows the result 1) “defgh” 2) abc

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

Q7) Explain about the Classes,methods,objects


Class
In Java everything is encapsulated under classes.
 Class is the core of Java language. Class can be defined as a template/ blueprint that
describe the behaviors /states of a particular entity.
 Class is the combination of member variables and member methods
 A class defines new data type
 Once defined this new type can be used to create object of that type.
 Object is an instance of class.
 A class is declared using class keyword.
 A class contain both data and code that operate on that data.
 The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods.
A class and an object can be related as follows: Consider an ice tray(like of cube shape)
as a class. Then ice cubes can be considered as the objects which is a blueprint of its class i.e of
ice tray.
Rules for Java Class
 A class can have only public or default(no modifier) access specifier.
 It can be either abstract, final or normal class.
 It must have the class keyword, and class must be followed by a legal identifier.
 It may optionally extend one parent class. By default, it will extend java.lang.Object.
 It may optionally implement any number of comma-separated interfaces.
 The class's variables and methods are declared within a set of curly braces {}.
Syntax:
class classname
{
Member variables
Member Methods
}
A simple class example
Suppose, Student is a class and student's name, roll number, age will be its property. Lets
see this in Java syntax
class Student.
{
String name;
int rollno;
int age;
}
When a reference is made to a particular student with its property then it becomes
an object, physical existence of Student class.
Student std=new Student();
After the above statement std is instance/object of Student class. Here the new keyword
creates an allocates memory for the object and assign it to the std variable. It will have physical
existence and get memory in heap area. The new operator dynamically allocates memory for
an object
Methods Declaration:
1. A Class with only data fields has no life
2. The programmer must add methods that are necessary for manipulating the data
contained in the class.
3. Methods are declared inside the body of the class but immediately after the declaration
of variables

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:

<classname> objname = new <classname()>


 “classname” represents name of the class
 “objname” is valid variable name treated as object.
 “new” is called dynamic memory allocation operator
 “new” allocates sufficient amount of memory space for the data members for a class
 “classname ()” represents constructor

Ex:
student obj=new student()

Syntax-2 for defining an OBJECT:

<classsname> objname; //object declaration


Objname = new <classname()>; //object referencing

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;

addition(int x,int y)//parameterized constructor


{
a=x;
b=y;
}

addition(addition dobj)//copy constructor


{
a=dobj.a;
b=dobj.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.

Q9)Explain about Static Variable and Method in Java


A) Static keyword in java is mainly used to save memory as with the help of static we can
declare data one time and access it in a whole program where we need the same data
more than one time in a program. After creating static keyword there is no need to declare
that data again and again. Static keyword can be used with:
1)Block
2)Method
3)Variable
Static Block
In Java, a static block is a special block of code within a class that gets executed only once
when the class is loaded into memory by the Java Virtual Machine (JVM). It is used to initialize
static variables or to perform any one-time initialization tasks that need to be done before the class
is used.
Key points about static blocks:
1. They are executed when the class is loaded into memory, before the creation of any objects
of that class.
2. They are declared using the static keyword followed by curly braces {}.
3. They cannot access non-static members (variables or methods) directly, as they are
executed before the object creation.
4. You can have multiple static blocks in a class, and they will be executed in the order they
appear in the class.
Syntax:
Class classname
{
Static
{
}
}
Ex:
Class hari
{
Static
{
System.out.println(“SKSD”);
}
Public static void main(String args[ ])
{
System.out.println(“Life Science Students”);
}
}

Static Variable With Example In JAVA


 Any variable when declared with the keyword “static” is known as static
variable or class variable in JAVA. Static variable is used to fulfill the common properties of
all objects.
 For example: institute name of students is common for all students so it will be declared as
static variable in JAVA. The static variable gets memory at class loading time only once in
class area.
Syntax of static variable:
static <DataType> <variable_name>;
For example:
static int age;
Important issues About Static Variabler:
 Static variables are also known as Class variables which are declared with the “static”
keyword in a class.
 A single copy of each variable per class is to be shared by all instances of the class.
 Static variables are stored in static memory.
 When the program starts static variables are created and when the program stops, static
variables are destroyed.
 Default values of static variables are same as instance variables. For numbers the default
value is 0, for Boolean the default value is false and for object references the default value
is null.
 Static variables can be accessed by calling with the class name. It does not need any
object.
 Static variables are initialized only one time, i.e. at the start of the execution. These
variables will be initialized first, before the initialization of any instance variables.
Ex:
class Student
{
int rollno;
String name;
static String college ="SKSD"; //Static Variable gets memory once
/*Constructor of Student class*/
Student(int r,String n)
{
rollno = r;
name = n;
}

/*Method For Displaying Student Details*/


void display()
{
System.out.println(rollno+" "+name+" "+college); // print the value of roll no, name and college
}
}
class womenes
{
public static void main(String args[])
{
Student s1 = new Student(1,"Hari");
Student s2 = new Student(2,"Prasad");
s1.display(); // call the display function using the s1 object
s2.display(); // call the display function using the s2 object
}
}
Output:
1 Hari SKSD
2 Prasad SKSD
Static Method
 The static method is similar to class method of a class but with the difference that the static
method can be called through the name of class without creating any instance(object) of
that class.
 A static method is also called class method as it is related with a class and not with
individual instance of the class.
 It is important to note that static method can only access variables and other static methods
of a class.
 This is because static methods can be used even if no object of that class has been
created.
 In case from the static method try to access a non static variable then compilation error will
be generated as the static method does not know which non static field value to use.
Program Example of Static Method:
Let us take an example to show the use of static method.
Step 1: First we create a class Methods in which we declare two static methods:
class hari
{
static int a=10,b=20,c;
static void display()
{
c=a+b;
System.out.println("Result = "+c);
}
}
class ramu
{
public static void main(String args[])
{
hari.display();
}
}
Here in the above example there are static variables a,b,c accessed by a static method called
“static void display()”.
Here we call static method “static void display()” without using any object.
Just we call it by using classname.method(hari.display())

Q10) Explain about “this” keyword in Java


A)
Definition:
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a method or
constructor parameter).
this can also be used to:
 To refer to the current class instance variable.
 To invoke the current class method.
 To invoke the current class constructor.
 To pass the current object as a parameter to a method.
 To return the current object from a method.
 To pass the current object as a parameter to a constructor.
 To access the outer class instance from an inner class.
Syntax
this.memberName;
this.methodName();
this(parameters);

Ex:

this.a=a
this.display()
this(10,20)

Q11) Explain about “super keyword” in Java


A)
The super keyword in Java is used in subclasses to access superclass members
(attributes, constructors and methods).
Before we learn about the super keyword, make sure to know about Java inheritance.
Uses of super keyword
1. To call methods of the superclass that is overridden in the subclass.
2. To access attributes (fields) of the superclass if both superclass and subclass have attributes with
the same name.
3. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass
constructor.

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();
}
}

After Run this program it shows the following result


I am the Property of A
I am the Property of B
Q12) Explain about abstract classes and Methods in Java
A)
Abstract Classes:
Definition :
 Java abstract class is a class that can not be instantiated by itself, it needs
to be subclassed by another class to use its properties.
 An abstract class is declared using the “abstract” keyword in its class
definition.
 Abstract classes are a key component of OOP in Java, allowing you to
define incomplete classes that other classes can extend.

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:

abstract class Shape


{
int color;
// An abstract function
abstract void draw();
}

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.

Note: Write the program in the Notes

Q13) Explain about Dynamic Binding


A)
Dynamic binding in Java, also known as late binding or runtime binding, is a mechanism where the
method to be executed is determined at runtime rather than compile-time. This concept is a key
feature of polymorphism in object-oriented programming and plays a significant role in how Java
handles method overriding.
Key Concepts
1. Polymorphism:
o Dynamic binding is closely related to polymorphism, particularly method overriding. It
allows a subclass to provide a specific implementation of a method that is already
defined in its superclass.
2. Method Overriding:
o When a subclass overrides a method from its superclass, the method that gets
called is determined at runtime based on the object being referred to, not the
reference type.
Q14) Explain about Command Line Arguments in Java
A)
 The java command-line argument is an argument i.e. passed at the time of running the java
program.
 The arguments passed from the console can be received in the java program and it can be
used as an input.
 So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java

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]);
}
}

 The above program takes an argument at run time


 It takes the Argument as String
 If we want to take the Integer or Float as Input then we must use the following
Methods

1. Integer.parseInt( ) -> It Is used to convert any String into Integer Datatype


2. Float.parseFloat( ) -> It is used to convert any String into Float Datatype

Ex:
Integer.parseInt(args[0]);
Float.parseFloat(args[1])

Q) Explain about Inheritance in Java


A) Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system)
 The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
 Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Super class is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to
o
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
 The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
 In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
 There are various types of Inheritances are available in java
1. Single Inheritance 2. Mulitple Inheritance 3. Multilevel Inheritance
4. Hierarchical Inheritance 5. Hybrid Inheritance
Single Inheritance : In single inheritance, a single subclasses inherit the features of one
superclass. In image below, the class A serves as a base class for the derived class B.

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();

System.out.println("Access data from b to a");


obj1.display1();
obj1.display2();

System.out.println("Access data from c to b,a");


obj2.display1();
obj2.display2();
obj2.display3();
}
}
In the above example the subclass 'b' use both the properties of 'b' (subclass) and
'a'(superclass) also at the same time 'c'(subclass) access the properties of both 'b'(subclass) and 'a'
(superclass)
Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.In below image, the class A serves as a base class for the derived
class B,C and D.

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.

Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above types of


inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is
also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

You might also like