0% found this document useful (0 votes)
6 views35 pages

JPR CH2 Classes Objects Methods

Uploaded by

spidy131415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views35 pages

JPR CH2 Classes Objects Methods

Uploaded by

spidy131415
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming Ch-2 Classes, Objects and Methods Marks: 24

Q. Define constructor. Explain parameterized constructor with example.


Constructor:
 A constructor is a special member which initializes an object immediately upon creation.
 It has the same name as class name in which it resides and it is syntactically similar to any
method.
 When a constructor is not defined, java executes a default constructor which initializes all
numeric members to zero and other types to null or spaces.
 Once defined, constructor is automatically called immediately after the object is created
before new operator completes.
Parameterized constructor: When constructor method is defined with parameters inside it,
different value sets can be provided to different constructor with the same name.
Example
Class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l; breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
[Link](“Area : ” +([Link]*[Link])); // o/p Area : 20
[Link](“Area : ” +([Link]*[Link])); // o/p Area : 42
}
}

Q. What is command line arguments explain with example


 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.
 Arguments are passed as a String array to the main method of a class. The first element
(element 0) is the first argument passed not the name of the class.
Example: we are printing all the arguments passed from the command-line. For this purpose, we
have traversed the array using for loop.
class A
{
public static void main(String args[])
{
for(int i=0;i<[Link];i++)
[Link](args[i]);
}
}
How to Run:
compile by > javac [Link]
run by > java A C C++ VB Java 10

output:
Vijay T. Patil
1
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
C
C++
VB
Java
10

Q. Explain varargs: variable length arguments with example


The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument we will have to
pass in the method, varargs is the better approach.
Syntax of varargs: The varargs uses ellipsis i.e. three dots after the data type.
return_type method_name(data_type... variableName){}
Example:
class VarargsExample1
{
static void display(String... values)
{
[Link]("display method invoked ");
for(String s:values)
{
[Link](s);
}
}

public static void main(String args[])


{
display(); //zero argument
display(“hello”); // one argument
display("my","name","is","varargs"); //four arguments
}
}
Output:
display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs

Q. What is garbage collection in java? Explain


 When the object is not needed any more, the space occupied by such objects can be
collected and use for later reallocation. Java performs release of memory occupied by
unused objects automatically, it is called garbage collection.
 Since objects are dynamically allocated by using the new operator, you might be wondering
how such objects are destroyed and their memory released for later reallocation. In some
languages, such as C++, dynamically allocated objects must be manually released by use of a
delete operator. Java takes a different approach; it handles deallocation for you
automatically. The technique that accomplishes this is called garbage collection.

Vijay T. Patil
2
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
 JVM runs the garbage collector (gc) when it finds time. Garbage collector will be run
periodically but you cannot define when it should be called.
 We cannot even predict when this method will be executed. It will get executed when the
garbage collector, which runs on its own, picks up the object.
Example:
public class A
{
int p, q;
A()
{
p = 10;
p = 20;
}
}
class Test
{
public static void main(String args[])
{
A a1= new A();
A a2= new A();
a1=a2; // it deallocates the memory of object a1
}
}

Q. Explain finalize method


 Sometime an object will need to perform some specific task before it is destroyed such as
closing an open connection or releasing any resources held. To handle such
situation finalize() method is used.
 finalize()method is called by garbage collection thread before collecting object. Its the last
chance for any object to perform cleanup utility.
 The garbage collector runs periodically, checking for objects that are no longer referenced
by any running state or indirectly through other referenced objects. Right before an asset is
freed, the java run time calls the finalize()method on the object.
Syntax:
protected void finalize()
{
// finalization code here
}

Q. Describe public and private access specifiers


Q. Describe public and private access specifiers
Q. Describe access control parameters with suitable example.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class. There are 4 types of java access modifiers:
 public
 private
 default (Friendly)
 protected

Public: Public Specifiers achieves the highest classes are in the same package or in another
level of accessibility. Classes, methods, and package.
fields declared as public can be accessed from Example: public int number;
any class in the Java program, whether these Public void sum() {-------------}
Vijay T. Patil
3
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

Private: Private Specifiers achieves the lowest


level of accessibility. private methods and
fields can only be accessed within the same
class to which the methods and fields belong.
private methods and fields are not visible
within subclasses and are not inherited by
subclasses. So, the private access specifier is
opposite to the public access specifier. Using
Private Specifier we can achieve
encapsulation and hide data from the outside
world.

Default (Friendly Access): When no access


modifier is specified, the member defaults to
a limited version of public accessibility known
as “friendly” level of access. Using default
specifier we can access class, method, or field
which belongs to same package, but not from
outside this package.

Protected: The visibility level of a “protected”


field lies in between the public access and
friendly access. Methods and fields declared
as protected can only be accessed by the
subclasses in other package or any class
within the package of the protected
members' class. Note that non sub classes in
other packages cannot access the “protected”
members.
Access Levels
Modifier Same class Subclass Other classes Sub class Non sub class
Same package In same package In other classes In other classes
Public Yes Yes Yes Yes Yes
Protected Yes Yes Yes Yes No
Friendly Yes Yes Yes No No
(default)
Private Yes No No No No

Q. Explain use of following methods: i) indexOf() ii) charAt() iii) substring() iv) replace()

Vijay T. Patil
4
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Q. Describe following string class method with example: (i) length() (ii) equals() (iii) charAt() (iv)
compareTo()
Q. Explain substring(), concat(), replace(), trim() method of class string.
The [Link] class provides a lot of methods to work on string. By the help of these methods,
we can perform operations on string such as trimming, concatenating, converting, comparing,
replacing strings etc.
toLowerCase():Converts all of the characters in this String to lower case.
Syntax: [Link]()
Example: String s="Sachin";
[Link]([Link]());
Output: sachin

toUpperCase():Converts all of the characters in this String to upper case


Syntax: [Link]()
Example:
String s="Sachin";
[Link]([Link]());
Output: SACHIN

trim():Returns a copy of the string, with leading and trailing whitespace omitted.
Syntax: [Link]()
Example:
String s=" Sachin ";
[Link]([Link]());
Output:Sachin

replace():Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
Syntax: [Link](‘x’,’y’)
Example:
String s1="Java is a programming language. Java is a platform.";
String s2=[Link]("Java","Kava"); //replaces all occurrences of "Java" to "Kava"
[Link](s2);
Output: Kava is a programming language. Kava is a platform.

charAt():Returns the character at the specified index.


Syntax: [Link](n)
Example:
String s="Sachin";
[Link]([Link](0));
[Link]([Link](3));
Output:
S
h

equals():The String equals() method compares the original content of the string. It compares values
of string for equality.
Syntax: [Link](s2)
Example:
String s1="Sachin";
String s2="Sachin";
String s3="Saurav"
[Link]([Link](s2)); //true

Vijay T. Patil
5
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]([Link](s3)); //false
Output:
True
False

equalsIgnoreCase():comparing two Strings by ignoring case.


Syntax: [Link](s2)
Example:
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2)); //false
[Link]([Link](s3)); //true
Output:
False
True

compareTo(): The String compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 : positive value
s1 < s2 : negative value
Syntax: [Link](s2)
Example:
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2)); //0
[Link]([Link](s3)); //1(because s1>s3)
[Link]([Link](s1)); //-1(because s3 < s1 )

length():The string length() method returns length of the string.


Syntax: [Link]()
Example:
String s="Sachin";
[Link]([Link]());
Output: 6

concat(): string concatenation forms a new string that is the combination of multiple strings.
Syntax: [Link](s2)
Example:
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);
Output: Sachin Tendulkar

Substring(): A part of string is called substring. In other words, substring is a subset of another string.
Syntax: [Link](n)
Example:
String s="Sachin Tendulkar";
[Link]([Link](6));
Output: Tendulkar
Vijay T. Patil
6
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

substring(n,m): Gives substring starting from nth character up to mth .


Syntax: [Link](n,m)
String s="Sachin Tendulkar";
[Link]([Link](0,6));
Output: Sachin

indexOf():Gives the position of the first occurrence of ‘x’ in the string s1.
Syntax: [Link](‘x’)
Example:
String s1=”sachin”;
[Link](‘a’);
Output: 1
[Link](‘x’,n): Gives the position of ‘x’ that occurs after nth position in the string s1.
Example:
String s1=”sanjay”; [Link](‘a’,2);
Output: 4

valueOf():The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.
Syntax: [Link](p)
Example:
int a=10;
String s=[Link](a);
[Link](s+10);
Output: 1010

endsWith():This method tests if this string ends with the specified suffix.
Syntax: endsWith(String suffix)
Example:
String Str = new String("This is really not immutable!!");
boolean retVal;
retVal = [Link]( "immutable!!" );
[Link]("Returned Value = " + retVal );
retVal = [Link]( "immu" );
[Link]("Returned Value = " + retVal );
Output:
Returned Value = true
Returned Value = false

startsWith(): This method has two variants and tests if a string starts with the specified prefix
beginning a specified index or by default at the beginning.
Syntax: startsWith(String prefix) or startsWith(String prefix, int toffset)
Example:
String Str = new String("Welcome to [Link]");
[Link]("Return Value :" );
[Link]([Link]("Welcome") );
[Link]("Return Value :" );
[Link]([Link]("Tutorials") );
Output:
Return Value : true
Return Value : false

Vijay T. Patil
7
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
StringBuffer Class Methods
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.
Append():The append() method concatenates the given argument with this string.
Syntax: [Link](s2)
Example:
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java"); //now original string is changed
[Link](sb); //output: Hello Java

Insert():The insert() method inserts the given string with this string at the given position.
Syntax: [Link](n,s2)
Example:
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java"); //now original string is changed
[Link](sb); //prints HJavaello

Replace():The replace() method replaces the given string from the specified beginIndex and
endIndex.
Syntax: replace(int start, int end, String str)
Example:
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb); //prints HJavalo

delete():The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
Syntax: delete(int start, int end)
Example:
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo

reverse(): The reverse() method of StringBuilder class reverses the current string.
Example:
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);
Output: olleH

setCharAt(): Modifies the nth character to x.


Example:
StringBuffer s1= new StringBuffer(“vijay”);
[Link](3,’e’);
Output: vijey

deleteCharAt():This is the deleteCharAt() function which is used to delete the specific character from
the buffered string by mentioning that's position in the string.
StringBuffer s1 = new StringBuffer("vijay");
[Link](2);
Output: viay

Vijay T. Patil
8
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
setLength(): This method sets the length of the character sequence. Sets the length of the string s1
to n. if n<[Link]() s1 is truncated. If n>[Link]() zeros are added to s1.
Syntax: [Link](n)
Example:
StringBuffer sb = new StringBuffer("Java Programming");
[Link](sb + "\nLength = " + [Link]()); // Java Programming Length = 16
[Link](4);
[Link](sb + "\nLength = " + [Link]()); // Java Length = 4

Q. Differentiate between string class and stringBuffer class

String class StringBuffer class


String is a major class StringBuffer is a peer class of String
Length is fixed (immutable) Length is flexible (mutable)
Contents of object cannot be modified Contents of object can be modified
Object can be created by assigning String Objects can be created by calling constructor of
constants enclosed in double quotes. StringBuffer class using “new”
Ex:- String s=”abc”‖; Ex:- StringBuffer s=new StringBuffer (“abc”);

Q. Explain the declaration and use of vector using proper example.


Q. Explain the following method of vector class (i) elementAt() (ii) addelement() (iii)
insertelementAt() (iv) removeelement()
Vector class is in [Link] package of java. Vector is dynamic array which can grow automatically
according to the requirement. Vector does not require any fix dimension like String array and int
array. Vectors are used to store objects that do not have to be [Link] contains many
useful methods.
Vectors are created like arrays. It has three constructor methods
 Vector list = new Vector(); //declaring vector without size
 Vector list = new Vector(3); //declaring vector with size
 Vector list = new Vector(5,2); //create vector with initial size and whenever it need to
grows, it grows by value specified by incrementcapacity

Method Name Task performed


[Link]() It returns the first element of the vector.
[Link]() It returns last element of the vector
[Link](item) Adds the item specified to the list at the end.
[Link](n) Gives the name of the object at nth position
[Link]() Gives the number of objects present in vector
[Link]() This method returns the current capacity of the vector.
[Link](item) Removes the specified item from the list.
[Link](n) Removes the item stored in the nth position of the list.
[Link]() Removes all the elements in the list.
[Link](item, n) Inserts the item at nth position.
[Link](object element) This method checks whether the specified element is present in
the Vector. If the element is been found it returns true else false.
[Link](array) Copies all items from list of array.

Q. Differentiate between array and vector


Vijay T. Patil
9
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

Array Vector
An array is a structure that holds multiple values The Vector is similar to array holds multiple
of the same type. objects and like an array; it contains components
that can be accessed using an integer index.
An array is a homogeneous data type where it Vectors are heterogeneous. You can have
can hold only objects of one data type. objects of different data types inside a Vector.
After creation, an array is a fixed-length The size of a Vector can grow or shrink as
structure. needed to accommodate adding and removing
items after the Vector has been created.
Array can store primitive type data element. Vector are store non-primitive type data
element.
Array is unsynchronized i.e. automatically Vector is synchronized i.e. when the size will be
increase the size when the initialized size will be exceeding at the time; vector size will increase
exceed. double of initial size.
Declaration of an array : Declaration of Vector:
int arr[] = new int [10]; Vector list = new Vector(3);
Array is the static memory allocation. Vector is the dynamic memory allocation.
Array allocates the memory for the fixed size ,in Vector allocates the memory dynamically means
array there is wastage of memory. according to the requirement no wastage of
memory.
No methods are provided for adding and Vector provides methods for adding and
removing elements. removing elements.
In array wrapper classes are not used. Wrapper classes are used in vector.
Array is not a class. Vector is a class.

Q. Write methods from wrapper class to: (i) convert a string to primitive integer (II) valueOf().
Q. What are the applications of wrapper classes? Explain integer wrapper class.
Q. List various wrapper classes. Give any four methods of Integer wrapper class.
Q. What are wrapper classes? Give the following wrapper class methods with syntax and use. (a)
To convert integer number to string (b) To convert numeric string to integer number.
Q. Define wrapper class. Give the following wrapper class methods with syntax and use: 1) To
convert integer number to string. 2) To convert numeric string to integer number. 3) To convert
object numbers to primitive numbers using typevalue() method.
Vectors cannot handle primitive data types like int, float, long, char and double. Primitive data types
may be converted into object types by using the wrapper classes.
The wrapper classes for numeric primitives have the capability to convert any valid number in string
format into its corresponding primitive object. For example “10" can be converted into an Integer by
using: Integer intVal = new Integer("10");
Simple data types and their corresponding wrapper class types are as follows:
Simple type Wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long

Vijay T. Patil
10
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Converting primitive numbers to object numbers using constructor methods
Constructor calling Conversion action
Integer IntVal = new Integer(i); Primitive integer to Integer objects.
Float floatVal = new Float(f); Primitive float to Float object.
Double DoubleVal = new Double(d); Primitive double to Double object.
Long LongVal = new Long(l); Primitive long to Long object.
Note: i, f, d, and l are primitive data values denoting int, float, double and long data types. They may
be constants or variables.

Converting object numbers to primitive numbers using typeValue() method


Method calling Conversion action
int i = [Link](); Object to primitive integer.
float f = [Link](); Object to primitive float.
long l = [Link](); Object to primitive long.
double d = [Link](); Object to primitive double.

Converting numbers to Strings using to String() method


Method calling Conversion action
str = [Link](i); Primitive integer to string.
str = [Link](f); Primitive float to string.
str = [Link](d); Primitive double to string.
str = [Link](l) Primitive long to string.

Converting String objects to numeric objects using the static method ValueOf()
Method calling Conversion action
DoubleVal = [Link](str); Converts string to Double object.
FloatVal = [Link](str); Converts string to Float object.
IntVal = [Link](str); Converts string to Integer object.
LongVal = [Link](str); Converts string to Long object.

Converting numeric strings to primitive numbers using Parsing methods


Method Calling Conversion action
int i = [Link](str); Converts string to primitive integer
long i = [Link](str); Converts string to primitive long

Q. What is Autoboxing and Unboxing


The Autoboxing and Unboxing was released with the Java 5. During assignment, the automatic
transformation of primitive type (int, float, double etc.) into their object equivalents or wrapper
type (Integer, Float, Double,etc) is known as Autoboxing. During assignment or calling of
constructor, the automatic transformation of wrapper types into their primitive equivalent is known
as Unboxing.
Example:
int i = 0;
i = new Integer(5); // auto-unboxing
Integer i2 = 5; // autoboxing

Vijay T. Patil
11
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

Q. Explain Enumerated Types


J2SE 5.0 allows us to use the enumerated type in java using enum keyword. Enum type is a type
which consists of fixed set of constant fields. This keyword can be used similar to the static final
constants.
Example:
public class Days
{
public static final int Sunday=0;
public static final int Monday=1;
public static final int Tuesday=2;
public static final int Wednesday=3;
public static final int Thursday=4;
public static final int Friday=5;
public static final int Saturday=6;
}
The above code can be rewritten using enumerated are:
Public enum Day{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
Advantages:
 Compile time type safety.
 We can use the enum keyword in switch statements.

Q. Describe use of “super” and “this” and “final” keyword with respect to inheritance with
example.
When we create super class that keeps the details of its implementation to itself (making it private).
Sometime the variable and methods of super class are private, so they will be available to subclass
but subclass cannot access it. In such cases there would be no way for a subclass to directly access
these variables on its own. Whenever a subclass needs a reference to it immediate super class, it can
do so by use of the keyword super.
Super have two general forms:
 The first calls the super class’s constructor.
 The second is used to access a member (variable or method) of the super class that has been
declared as private
Example use of super() class
class A { int i; }
// Create a subclass by extending class A.
class B extends A
{ int i; // this i hides the i in A
B(int a, int b)
{ super.i = a; // i in A
i = b; // i in B
}
void show()
{
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}

Vijay T. Patil
12
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
[Link]();
}
}

The This Keyword


The keyword this is useful when you need to refer to instance of the class from its method. This can
be used inside any method to refer to the current object. That is, this is always a reference to the
object on which the method was invoked. You can use this anywhere a reference to an object of the
current class' type is permitted. The keyword helps us to avoid name conflicts. In the program we
have declare the same name for instance variable and local variables. Now to avoid the confliction
between them we use this keyword.
//example of this keyword
class Student11
{
int id;
String name;
Student11(int id,String name)
{
[Link] = id;
[Link] = name;
}
void display()
{
[Link](id+" "+name);
}
public static void main(String args[])
{
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
Final keywords The keyword final has three uses. First, it can be used to create the equivalent of a
named constant.( in interface or class we use final as shared constant or constant.) other two uses of
final apply to inheritance
Using final to Prevent Overriding While method overriding is one of Java‟s most powerful features,
there will be times When you will want to prevent it from occurring. To disallow a method from
being overridden, specify final as a modifier at the start of its declaration. Methods declared as final
cannot be overridden.

Vijay T. Patil
13
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

The following fragment illustrates final:


class A
{
final void meth()
{
[Link]("This is a final method.");
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
[Link]("Illegal!");
}
}
As base class declared method as a final , derived class can not override the definition of base class
methods.

Q. Describe final method and final variable with respect to inheritance.


final method: making a method final ensures that the functionality defined in this method will never
be altered in any way, ie a final method cannot be overridden.
Syntax:
final void findAverage()
{
//implementation
}
Example of declaring a final method:
class A
{
final void show()
{
[Link](“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
[Link](“in show of B”);
}
}

Final variable: the value of a final variable cannot be changed. final variable behaves like class
variables and they do not take any space on individual objects of the class.
Example of declaring final variable: final int size = 100;

Vijay T. Patil
14
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

Q. Explain method overloading with suitable example


 Method Overloading means to define different methods with the same name but different
parameters lists and different definitions.
 It is used when objects are required to perform similar task but using different input
parameters that may vary either in number or type of arguments.
 Overloaded methods may have different return types.
 It is a way of achieving polymorphism in java.
Syntax:
 int add( int a, int b) // prototype 1
 int add( int a , int b , int c) // prototype 2
 double add( double a, double b) // prototype 3
Example :
class Sample
{
int addition(int i, int j)
{ return i + j ; }
String addition(String s1, String s2)
{ return s1 + s2; }
double addition(double d1, double d2)
{ return d1 + d2; }
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();
[Link]([Link](1,2));
[Link]([Link]("Hello ","World"));
[Link]([Link](1.5,2.2));
}
}

Q. What is difference between overloading and overriding methods


Q. Explain overriding. How is it different from overloading?
Method Overriding: There may be occasions when we want an object to respond to the same
method but have different behavior when that method is called. This is possible by defining a
method in the subclass that has the same name, same arguments and same return type as a method
in the superclass. Then, when that method is called, the method defined in the subclass is invoked
and executed instead of the one in the superclass. This is known as overriding.
Example:
class Super
{
int x;
Super (int x)
{ this.x=x; }
void display()
{ [Link](“Super x=”‖+x); }
}

Class Sub extends Super


Vijay T. Patil
15
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
{
int y; Sub( int x, int y)
{
super (x);
this.y=y;
}
void display()
{
[Link](“Super x=”‖ +x);
[Link](“Sub y=‖” +y);
}
}
class overrideTest
{
public static void main(String arg[])
{
Sub s1= new Sub(100,200);
[Link]();
}}
Method Overloading Method Overriding
It happens within the same class It happens between super class and subclass
Method signature should not be same Method signature should be same.
Method can have any return type Method return type should be same as super
class method
Overloading is early binding or static binding Overriding is late binding or dynamic binding
They have the same name but, have different They have the same name as a superclass
parameter lists, and can have different return method. They have the same parameter list as a
types. superclass method. They have the same return
type as a superclass method
It is resolved at compile time It is resolved at runtime.
Inheritance does not blocked by method Method overriding blocks the inheritance.
overloading.
One method can overload unlimited number of Method overriding can be done only once per
times. method in the sub class.

Q. Explain Dynamic method dispatch


 Dynamic method dispatch is the mechanism by which a call to a overridden method is
resolved at runtime rather than at compile time
 It forms the basis for runtime polymorphism
 When an overridden method is called through a super class reference
 java determines which method to execute based upon the type of the object being referred
at the time the call is made
Example:
import [Link].*;
class A
{
void show()
{
[Link]("in show of A");
}
}

Vijay T. Patil
16
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class B extends A
{
void show()
{
[Link]("in show of B");
}
}

class C extends B
{
void show()
{
[Link]("in show of C");
}
}

class DynaMethod
{
public static void main(String args[])
{
A a = new A(); // object of class A
B b = new B(); // object of class B
C c = new C(); // object of class C
A r; // obtain a reference of type A
r = a; //r refer to object of A
[Link](); // call show() of A
r = b; //r refer to object of B
[Link](); // call show() of B
r = c; //r refer to object of C
[Link](); // call show() of C
}
}
Output:
in show of A
in show of B
in show of C
Reference of class A stores the reference of class A, class B and class C alternatively. Every call to
show() method would result in execution of show() method of that class whose reference is
currently stored by a reference of class A.

Q. Explain Static Member


When a number of objects are created from the same class, each instance has its own copy of class
variables. But this is not the case when it is declared as static. Static method or a variable is not
attached to a particular object, but rather to the class as a whole. They are allocated when the class
is loaded. If some objects have some variables which are common then these variables or methods
must be declared static. To create a static variable, precede its declaration with keyword static.
Static variables need not be called on any object.
Example:
int a; // normal variable
static int a; //static variable

Vijay T. Patil
17
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Program for static variables
class s
{
int a,b;
static int c;
}
class statictest
{
public static void main(String args[])
{
s ob1=new s();
s ob2=new s();
s ob3=new s();
}
}
In above program variable a and b are declared as int variable whereas the variable c is declared as
static variable. Static variable will be common between all the objects.

When we accessing variable as ‘a’ we cannot access it directly without the reference of the object
because ‘a’ exist in all three objects. So to access the value of ‘a’ we must link it with the name of the
object. But the ‘c’ is static variable and it is common between all the objects so we can access it
directly. But when we are accessing it outside the class in which it is declared, we must link it with
the name of the class i.e. with S as S.c=20;

Q. Explain abstract class with suitable example.


 A class that is declared with abstract keyword is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Another way, it shows only important things to the user and
hides the internal details.
 A method must be always redefined in a subclass of an abstract class, as abstract class
does not contain method body. Thus abstract makes overriding compulsory.
 Class containing abstract method must be declared as abstract.
 You cannot declare abstract constructor, and so, objects of abstract class cannot be
instantiated.
Syntax :
abstract class < classname>
{
abstract method1(…);
method2(….);
. .}
Example
abstract class A
Vijay T. Patil
18
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
{
abstract void disp();
void show()
{
[Link](“show method is not abstract”);
}}
class B extends A
{
void disp()
{
[Link](“inside class B”);
}}
class test
{
public static void main(String args[])
{
B b = new B();
[Link]();
[Link]();
}}
Output :
show method is not abstract
inside class B

Programs:
Q. Write a program to convert a decimal number to binary form and display the value
import [Link].*;
import [Link].*;
class dtob
{
public static void main(String args[]) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the decimal value=");
String hex=[Link]();
int i=[Link](hex);
String bi=[Link](i);
[Link]("Binary number="+bi);
}
}
Output:
Enter the decimal value=12
Binary number=1100

Vijay T. Patil
19
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Q. Define a class item having data member code and price. Accept data for one object and display
it.
import [Link].*;
class Item_details
{
int code;
float price;
Item_details()
{
code=0;
price=0;
}
Item_details(int e,float p)
{
code=e;
price=p;
}
void putdata()
{
[Link]("Code of item :"+code);
[Link]("Price of item:"+price);
}
public static void main(String args[]) throws IOException
{
Int co;
Float pr;
BufferedReaderbr=new BufferedReader (new InputStreamReader([Link]));
[Link]("enter code and price of item");
co=[Link]([Link]());
pr=[Link]([Link]());
Item_details obj=new Item_details(co,pr);
[Link]();
}
}

Q. Write a program to implement a vector class and its method for adding and removing elements.
After remove display remaining list.
import [Link].*;
import [Link].*;
import [Link].*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Character s5=new Character('a');

Vijay T. Patil
20
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
Character s6=new Character('b');
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
[Link](s5);
[Link](s6);
[Link](s7);
[Link](s8);
[Link](v);
[Link](s2);
[Link](4);
[Link](v);
}
}

Q. Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10, 20). Remove
element at 3rd and 4th position. Insert new element at 3 rd position. Display the original and current
size of vector.
import [Link].*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
[Link](new Integer(10));
[Link](new Integer(20));
[Link](new Integer(30));
[Link](new Integer(40));
[Link](new Integer(10));
[Link](new Integer(20));
[Link] println([Link]()); // display original size
[Link](2); // remove 3rd element
[Link](3); // remove 4th element
[Link](11,2) // new element inserted at 3rd position
[Link]("Size of vector after insert delete operations: " + [Link]());
}
}

Q. Write a program to accept a number as command line argument and print the number is even
or odd
public class oe
{
public static void main(String key[])
{
int x=[Link](key[0]);
if (x%2 ==0)
{
[Link]("Even Number");
Vijay T. Patil
21
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
}
else
{
[Link]("Odd Number");
}
}
}

Q. Define a class ‘employee’ with data members empid, name and salary. Accept data for five
objects using Array of objects and print it.
class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader([Link]));
[Link]("Enter Emp number : ");
empid=[Link]([Link]());
[Link]("Enter Emp Name : ");
name=[Link]();
[Link]("Enter Emp Salary : ");
salary=[Link]([Link]());
}
void show()
{
[Link]("Emp ID : " + empid);
[Link](“Name : " + name);
[Link](“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[5];
for(inti=0; i<5; i++)
{
e[i] = new employee();
e[i].getdata();
}
[Link](" Employee Details are : ");
for(inti=0; i<5; i++)
e[i].show();
}
}

Q. Write a program to accept first name, middle name and surname in three different strings and
then concatenate the three strings to make full name.

Vijay T. Patil
22
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
import [Link].*;
class StringConcat
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String str1,str2,str3,namestr="";
[Link]("Enter first name:");
str1=[Link]();
[Link]("Enter middle name:");
str2=[Link]();
[Link]("Enter last name:");
str3=[Link]();
namestr = [Link](str1);
namestr = namestr + " ";
namestr = [Link](str2);
namestr = namestr + " ";
namestr = [Link](str3);
[Link]("Your FULL NAME is : " + namestr);
}}

Q. Write a program to create and sort all integer array.


class bubble
{
public static void main(String args[])
{
int a[]={10,25,5,20,50,45,40,30,35,55};
int i=0;
int j=0;
int temp=0;
int l=[Link];
for(i=0;i<l;i++)
{
for(j=(i+1);j<l;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
[Link]("Ascending order of numbers:");
for(i=0;i<l;i++)
[Link](""+a[i]);
}
}

Q. Write a program to check whether the given string is palindrome or not


import [Link].*;

Vijay T. Patil
23
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
import [Link].*;
import [Link].*;
class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter String:");
String word=[Link]( );
int len=[Link]( )-1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{
if([Link](l)==[Link](r))
{
l++;
r--;
}
else
{
flag=0; break;
}
}
if(flag==1)
{
[Link]("palindrome");
}
else
{ [Link]("not palindrome"); }
}}

Q. Program to define a class student with four data members such as name, roll no, sub1 and
sub2. Define appropriate methods to initialize and display the values of data members also
calculate total marks and percentage scored by student
class stu
{
String name;
int rollno;
float sub1, sub2;
stu(String n, int r, float s1, float s2)
{
name=n;
rollno=r;
sub1=s1;
sub2=s2;
}

void display()
{
[Link]("Name="+name);
Vijay T. Patil
24
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]("Rollno="+rollno);
[Link]("Sub1 marks="+sub1);
[Link]("Sub2 marks="+sub2);
}

void calculate()
{
float total=sub1+sub2;
[Link]("total="+total);
float per=(total/200)*100;
[Link]("Percentage="+per);
}
}

class student
{
public static void main(String args[])
{
stu s=new stu("Vijay",11,90f,80f);
[Link]();
[Link]();
}
}

Q. Define a class circle having data members pi and radius. Initialize and display values of data
members also calculate area of circle and display it.
class abc
{
float pi,radius;
abc(float p, float r)
{
pi=p;
radius=r;
}

void area()
{
float ar=pi*radius*radius;
[Link]("Area="+ar);
}

void display()
{
[Link]("Pi="+pi);
[Link]("Radius="+radius);
}
}

class area
{
public static void main(String args[])
Vijay T. Patil
25
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
{
abc a=new abc(3.14f,5.0f);
[Link]();
[Link]();
}
}

Q. Program to implement following multilevel inheritance.

import [Link].*;
class Square //super class
{
int length;
Square(int x)
{
length=x;
}
void area() //method to calculate area of square
{
int area=length*length;
[Link]("Area of Square="+area);
}
}
class Rectangle extends Square
//inherit class rectanglefrom class square
{
int breadth;
Rectangle(int x, int y)
{
super(x); //calling super class constructor
breadth=y;
}
void rectArea()
{
int area1=length*breadth;
[Link]("Area of Rectangle="+area1);
}
}

class Box extends Rectangle


//inherit class Box from class Rectangle
{

Vijay T. Patil
26
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
int height;
Box(int x, int y, int z)
//calling rectangle class constructor
{
super(x,y);
height=z; }
void volume()
//method to display volume of box
{
int volume=length*breadth*height;
[Link]("Volume of Box="+volume);
} }

class Shape
{
public static void main(String args[])
//main method
{
Box b=new Box(10,20,30);
//creating object of Box class
[Link]();
[Link]();
[Link]();
}
}
Output:
Volume of Box=6000
Area of Rectangle=200
Area of Square=100

Q. Program to define class student with roll no. and name. Derive class attendance with member
as present days. Write method to calculate and print average attendance assuming today days as
180.
import [Link].*;
import [Link].*;
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno=r;
name=n;
}
void display()
{
[Link]("Roll No="+rollno);
[Link]("Name="+name);
}
}

class att extends student


{
Vijay T. Patil
27
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
double presentday;
att(int r, String n, int p)
{
super(r,n);
presentday=p;
}
void calculate()
{
double avg=(100*presentday)/180;
display();
[Link]("Present days="+presentday);
[Link]("Average Attendance="+avg);
}
}

class stuatt
{
public static void main(String args[])
{
att s1=new att(11,"vijay",150);
[Link]();
}
}
Output:
Roll No=11
Name=vijay
Present days=150.0
Average Attendance=83.33333333333333

Q. Program to implement the following single level inheritance.

class person
{
String name;
int age;
void getdata(String n, int a)
{
name=n;
age=a;
}

void putdata()
{
[Link]("Employee Details: ");

Vijay T. Patil
28
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]("Employee Name: "+name);
[Link]("Employee Age: "+age);
}}

class emp extends person


{
String emp_desig;
int emp_sal;
void getdata(String n, int a, String e, int s)
{
[Link](n,a);
emp_desig=e;
emp_sal=s;
}

void putdata()
{
[Link]();
[Link]("Employee's Designation: "+emp_desig);
[Link]("Employee's Salary; Rs. "+emp_sal);
}}

class emp1
{
public static void main(String args[])
{
emp e1=new emp();
[Link]("vijay",30,"Manager",50000);
[Link]();
}}

Output:
Employee Details:
Employee Name: vijay
Employee Age: 30
Employee's Designation: Manager
Employee's Salary; Rs. 50000

Q. Program to implement the following multi-level inheritance

Vijay T. Patil
29
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

class account
{
String custname;
int accno;
void getdata(String n, int a)
{
custname=n;
accno=a;
}
void putdata()
{
[Link]("Customers Account Details\n");
[Link]("Customers Name: "+custname);
[Link]("Customers Account Number: "+accno);
}
}

class savingacc extends account


{
int minbal;
int savbal;
void getdata(String n, int a, int m, int s)
{
[Link](n,a);
minbal=m;
savbal=s;
}
void putdata()
{
[Link]();
[Link]("Minimum Balance: "+minbal);
[Link]("Saving Balance: "+savbal);
}
}

Vijay T. Patil
30
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
class accdetail extends savingacc
{
int deposits;
int withdrawal;
void getdata(String n, int a, int m, int s, int d, int w)
{
[Link](n,a,m,s);
deposits=d;
withdrawal=w;
}
void putdata()
{
[Link]();
[Link]("Deposit: "+deposits);
[Link]("Withdrawal Amount: "+withdrawal);
}
}

class acc
{
public static void main(String args[])
{
accdetail a1=new accdetail();
[Link]("Vijay",123,500,10000,5000,2500);
[Link]();
}
}
Output:
Customers Account Details
Customers Name: Vijay
Customers Account Number: 123
Minimum Balance: 500
Saving Balance: 10000
Deposit: 5000
Withdrawal Amount: 2500

Q. Program to implement following inheritance

import [Link].*;
class sphere
{
int r;
float pi;

Vijay T. Patil
31
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

sphere(int r, float pi) //super class constructor


{
this.r=r;
[Link]=pi;
}
void volume() //method to display volume of sphere
{
float v=(4*pi*r*r)/3;
[Link]("Volume of Sphere="+v);
}
}

class hemisphere extends sphere //subclass defined


{
int a;
hemisphere(int r, float pi, int a)
{
super(r,pi);
this.a=a;
}
void volume() //method to display volume of hemisphere
{
[Link]();
float v=(a*pi*r*r*r)/3;
[Link]("Volume of Hemisphere="+v);
}
}

class volume
{
public static void main(String args[]) //main method
{
hemisphere h=new hemisphere(12, 3.14f, 2);
[Link]();
}
}

Output:
Volume of Sphere=602.88
Volume of Hemisphere=3617.28

Q. Implement following inheritance

Vijay T. Patil
32
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
import [Link].*;
abstract class shape
{
float dim1,dim2;
void getdata()
{
DataInputStream d=new DataInputStream([Link]);
try
{
[Link]("Enter the value of Dimension1: ");
dim1=[Link]([Link]());
[Link]("Enter the value of Dimension2: ");
dim2=[Link]([Link]());
}
catch(Exception e)
{
[Link]("General Error"+e);
}
}

void disp()
{
[Link]("Dimension1= "+dim1);
[Link]("Dimension2= "+dim2);
}
abstract void area();
}

class rectangle extends shape


{
double area1;
void getd()
{
[Link]();
}
void area()
{
area1=dim1*dim2;
[Link]("The Area of Rectangle is: "+area1);
}
}

class triangle extends shape


{
double area1;
void getd()
{
[Link]();
}

Vijay T. Patil
33
Java Programming Ch-2 Classes, Objects and Methods Marks: 24

void area()
{
area1=(0.5*dim1*dim2);
[Link]("The Area of Triangle is: "+area1);
}
}

class methodover1
{
public static void main(String args[])
{
rectangle r=new rectangle();
[Link]("For Rectangle");
[Link]();
[Link]();
[Link]();

triangle t=new triangle();


[Link]();
[Link]();
[Link]();
}
}

Output:
For Rectangle
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 5.0
Dimension2= 6.0
The Area of Rectangle is: 30.0
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 6.0
Dimension2= 7.0
The Area of Triangle is: 21.0

Q. Write a program to accept a password from the user and authenticate the user if password is
correct.
import [Link].*;
class test
{
public static void main(String a[]) throws Exception
{
String S1="Admin";
String S2="12345";
String username, userpwd;
try
{
BufferedReader b = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the user name");
username=[Link]();
Vijay T. Patil
34
Java Programming Ch-2 Classes, Objects and Methods Marks: 24
[Link]("Enter the password");
userpwd= [Link]();
if([Link](username) && [Link](userpwd))
{
[Link]("Welcome!! You are authenticated");
}
else
{
[Link]("You have entered wrong information!!");
}
}
catch(Exception e)
{
[Link]("I/O Error");
}
}
}
Output:
Enter the user name
Admin
Enter the password
12345
Welcome!! You are authenticated
Enter the user name
Admin
Enter the password
123
You have entered wrong information!!

Vijay T. Patil
35

You might also like