0% found this document useful (0 votes)
1 views16 pages

Unit Ii

DSE notes

Uploaded by

gayuhem27
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)
1 views16 pages

Unit Ii

DSE notes

Uploaded by

gayuhem27
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
You are on page 1/ 16

UNIT –II

Single Inheritance in Java

Single Inheritance is the simple inheritance of all, When a class extends another
class(Only one class) then we call it as Single inheritance.

The below diagram represents the single inheritance in java where Class B extends only
one class Class A.

Class B will be the Sub class and Class A will be one and only Super class.

Single Inheritance Example

publicclassClassA
{
publicvoiddispA()
{
System.out.println("disp() method of ClassA");
}
}
publicclassClassBextendsClassA
{
publicvoiddispB()
{
System.out.println("disp() method of ClassB");
}
publicstaticvoid main(Stringargs[])
{
//Assigning ClassB object to ClassB reference
ClassB b =newClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
Multiple inheritance in java:

Multiple Inheritance is nothing but one class extending more than one class.

Multiple Inheritance is basically not supported by many Object Oriented


Programming languages such as Java, Small Talk, C# etc.. (C++ Supports Multiple
Inheritance).

As the Child class has to manage the dependency of more than one Parent class. But you
can achieve multiple inheritance in Java using Interfaces.

Multilevel Inheritance in java:

In Multilevel Inheritance a derived class will be inheriting a parent class and as well
as the derived class act as the parent class to other class. As seen in the below
diagram. ClassBinherits the property of ClassA and again ClassB act as a parent
for ClassC. In Short ClassAparent for ClassB and ClassB parent for ClassC.
MultiLevel Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}

Hierarchical Inheritance in java:

In Hierarchical inheritance one parent class will be inherited by many sub classes. As
per the below example ClassA will be inherited by ClassB, ClassC and ClassD.

ClassA will be acting as a parent class for ClassB, ClassC and ClassD.
Hierarchical Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
ClassC c = new ClassC();
c.dispC();
c.dispA();
ClassD d = new ClassD();
d..dispD();
d.dispA();
}
}
Abstract class in java:

A class that is declared using “abstract” keyword is known as abstract class. It can have
abstract methods(methods without body) as well as concrete methods (regular methods
with body). A normal class(non-abstract class) cannot have abstract methods.

Abstract class declaration

An abstract class outlines the methods but not necessarily implements all the methods.

//Declaration using abstract keyword


abstract class A{
//This is abstract method
abstract void myMethod();

//This is concrete method with body


voidanotherMethod(){
//Does something
}
}
A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.

Abstract class cannot be instantiated which means you cannot create the object of it. To
use this class, you need to create another class that extends this this class and provides the
implementation of abstract methods

If a child does not implement all the abstract methods of abstract parent class, then the
child class must need to be declared abstract as well.

Example of Abstract class and method

abstract class MyClass{


public void disp(){
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}

class Demo extends MyClass{


public void disp2()
{
System.out.println("overriding abstract method");
}
public static void main(String args[]){
Demo obj = new Demo();
obj.disp2();
}
}
Define interface in java:

Using the keyword interface, you can fully abstract a class’ interface from its
implementation. That is, using interface, you can specify what a class must do, but not
how it does it.

Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body. In practice, this means that you can define
interfaces that don’t make assumptions about how they are implemented.

Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.

To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation.

By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.

Interfaces are designed to support dynamic method resolution at run time. Normally, in
order for a method to be called from one class to another, both classes need to be present
at compile time so the Java compiler can check to ensure that the method signatures are
compatible

Defining an Interface

An interface is defined much like a class. This is a simplified general form of an


interface:

access interface name { return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

return-type method-nameN(parameter-list);

type final-varnameN = value; }


When no access modifier is included, then default access results, and the interface is only
available to other members of the package in which it is declared. When it is declared as
public, the interface can be used by any other code

Implementation of interface:

Once an interface has been defined, one or more classes can implement that interface.

To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.

The general form of a class that includes the implements clause looks like this:

classclassname [extends superclass] [implements interface [,interface...]]

{ // class-body }

If a class implements more than one interface, the interfaces are separated with a comma.

If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface.

The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature specified in
the interface definition

class Client implements Callback {

public void callback(int p)

{ System.out.println("callback called with " + p); }

Interfaces can be extended:

One interface can inherit another by use of the keyword extends.

The syntax is the same as for inheriting classes.

When a class implements an interface that inherits another interface, it must provide

implementations for all methods defined within the interface inheritance chain.

EXAMPLE

interface A {

void meth1();

void meth2();
}

interface B extends A

{ void meth3(); }

MyClass implements B

public void meth1()

System.out.println("Implement meth1().");

public void meth2() { System.out.println("Implement meth2()."); }

public void meth3() { System.out.println("Implement meth3()."); } }

classIFExtend {

public static void main(String arg[]) {

MyClassob = new MyClass();

ob.meth1();

ob.meth2();

ob.meth3(); }

Final Method and Final Class in java with example:


Sometimes you may want to prevent a subclass from overriding a method in your
class. To do this, simply add the keyword final at the start of the method declaration in a
super class. Any attempt to override a final method will result in a compiler error

class base
{
final void display()
{
System.out.println("Base method called");
}
}

class Derived extends Base


{
void display() //cannot override
{
System.out.println("Base method called");
}
}
class finalMethod
{
public static void main(String[] args)
{
Derived d =new Derived();
d.display();
}
}
On compiling the above example, it will display an error

Final class

A final class can not be inherited/extended.

Java program to demonstrate example of final class.

1 importjava.util.*;
2
3 final class Base
4 {
5 public void displayMsg()
6 {
7 System.out.println("I'm displayMsg() in Base class.");
8 }
9 }
1
0 public class FinalClassExample extends Base
1 {
1 public void displayMsg1()
1 {
2 System.out.println("I'm displayMsg1() in Final class.");
1 }
3
1 public static void main(String []s)
4 {
1 FinalClassExample FCE=new FinalClassExample();
5 FCE.displayMsg();
1 FCE.displayMsg1();
6 }
1 }
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
Object Cloning in Java with example:
The object cloning is a way to create exact copy of an object. The clone() method of
Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone
we want to create. If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as
follows
Example of clone() method (Object cloning)
class Student18 implements Cloneable
{
int rollno;
String name;
Student18(int rollno,String name){
this.rollno=rollno;
this.name=name;
}

public Object clone()throws CloneNotSupportedException


{
return super.clone();
}

public static void main(String args[]){


try{
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
Inner class in java with example:

A non-static class that is created inside a class but outside a method is called member
inner class.
Syntax:
class Outer{
//code
class Inner{
//code
}
}

Java Member inner class example

In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Methods in array list with example:

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
The important points about Java ArrayList class are:
Java ArrayList class can contain duplicate elements.

Java ArrayList class maintains insertion order.

Java ArrayList class is non synchronized.

Java ArrayList allows random access because array works at the index basis.

In Java ArrayList class, manipulation is slow because a lot of shifting needs to be


occurred if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in above diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable interfaces in
hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAcce
ss, Cloneable, Serializable
Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection c) It is used to build an array list that is initialized with the elements
of the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.

Methods of Java ArrayList

Method Description

void add(int index, Object It is used to insert the specified element at the specified
element) position index in a list.

booleanaddAll(Collection c) It is used to append all of the elements in the specified


collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

void clear() It is used to remove all of the elements from this list.

intlastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.

Object[] toArray() It is used to return an array containing all of the elements in


this list in the correct order.
Object[] toArray(Object[] a) It is used to return an array containing all of the elements in
this list in the correct order.

boolean add(Object o) It is used to append the specified element to the end of a list.

booleanaddAll(int index, It is used to insert all of the elements in the specified


Collection c) collection into this list, starting at the specified position.

Object clone() It is used to return a shallow copy of an ArrayList.

intindexOf(Object o) It is used to return the index in this list of the first occurrence
of the specified element, or -1 if the List does not contain this
element.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be


the list's current size.

Java ArrayList Example


import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

String Class and its methods with examples:


String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java,
string is an immutable object which means it is constant and can cannot be changed
once it has been created.

Creating a String

There are two ways to create a String in Java


1. String literal
2. Using new keyword

String literal

In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 ="Welcome";


String str2 ="Welcome";

Using New Keyword

String str1 = new String("Welcome");


String str2 = new String("Welcome");

In this case compiler would create two different object in memory having the same string.

A Simple Java String Example

public class Example{


public static void main(String args[]){
//creating a string by java string literal
String str = "Beginnersbook";
chararrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);

//creating another java string str3 by using new keyword


String str3 = new String("Java String Example");

//Displaying all the three strings


System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Java String Methods

Here are the list of the methods available in the Java String class.

1. charcharAt(int index): It returns the character at the specified index. Specified index
value should be between 0 to length() -1 both inclusive. It throws
IndexOutOfBoundsException if index<0||>= length of String.
2. boolean equals(Object obj): Compares the string with the specified string and returns
true if both matches else false.
3. booleanequalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. intcompareTo(String string): This method compares the two strings based on the
Unicode value of each character in the strings.
5. intcompareToIgnoreCase(String string): Same as CompareTo method however it
ignores the case during comparison.
6. booleanstartsWith(String prefix, int offset): It checks whether the substring (starting
from the specified offset index) is having the specified prefix or not.
7. booleanstartsWith(String prefix): It tests whether the string is having specified prefix,
if yes then it returns true else false.
8. booleanendsWith(String suffix): Checks whether the string ends with the specified
suffix.
9. inthashCode(): It returns the hash code of the string.
10. intindexOf(intch): Returns the index of first occurrence of the specified character ch in
the string.
11. intindexOf(intch, intfromIndex): Same as indexOf method however it starts searching
in the string from the specified fromIndex.
12. intlastIndexOf(intch): It returns the last occurrence of the character ch in the string.
13. intlastIndexOf(intch, intfromIndex): Same as lastIndexOf(intch) method, it starts
search from fromIndex.
14. intindexOf(String str): This method returns the index of first occurrence of specified
substring str.
15. intlastindexOf(String str): Returns the index of last occurrence of string str.
16. String substring(intbeginIndex): It returns the substring of the string. The substring
starts with the character at the specified index.
17. String substring(intbeginIndex, intendIndex): Returns the substring. The substring
starts with character at beginIndex and ends with the character at endIndex.
18. String concat(String str): Concatenates the specified string “str” at the end of the string.
19. String replace(char oldChar, char newChar): It returns the new updated string after
changing all the occurrences of oldChar with the newChar.
20. boolean contains(CharSequence s): It checks whether the string contains the specified
sequence of char values. If yes then it returns true else false. It throws
NullPointerExceptionof ‘s’ is null.
21. String toUpperCase(Locale locale): Converts the string to upper case string using the
rules defined by specified locale.
22. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
23. public String intern(): This method searches the specified string in the memory pool
and if it is found then it returns the reference of it, else it allocates the memory space to
the specified string and assign the reference to it.
24. publicbooleanisEmpty(): This method returns true if the given string has 0 length. If
the length of the specified Java String is non-zero then it returns false.
25. public static String join(): This method joins the given strings using the specified
delimiter and returns the concatenated Java String
26. String replaceFirst(String regex, String replacement): It replaces the first occurrence of
substring that fits the given regular expression “regex” with the specified replacement
string.
27. String replaceAll(String regex, String replacement): It replaces all the occurrences of
substrings that fits the regular expression regex with the replacement string.
28. String[] split(String regex, int limit): It splits the string and returns the array of
substrings that matches the given regular expression. limit is a result threshold here.
29. String[] split(String regex): Same as split(String regex, int limit) method however it
does not have any threshold limit.
30. String toLowerCase(Locale locale): It converts the string to lower case string using the
rules defined by given locale.
31. public static String format(): This method returns a formatted java String
32. String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
33. String trim(): Returns the substring after omitting leading and trailing white spaces
from the original string.
34. char[] toCharArray(): Converts the string to a character array.
35. static String copyValueOf(char[] data): It returns a string that contains the characters of
the specified character array.
36. static String copyValueOf(char[] data, int offset, int count): Same as above method
with two extra arguments – initial offset of subarray and length of subarray.
37. voidgetChars(intsrcBegin, intsrcEnd, char[] dest, intdestBegin): It copies the characters
of srcarray to the dest array. Only the specified range is being copied(srcBegin to
srcEnd) to the destsubarray(starting fromdestBegin).
38. static String valueOf(): This method returns a string representation of passed
arguments such as int, long, float, double, char and char array.
39. booleancontentEquals(StringBuffersb): It compares the string to the specified string
buffer.
40. booleanregionMatches(intsrcoffset, String dest, intdestoffset, intlen): It compares the
substring of input to the substring of specified string.
41. booleanregionMatches(booleanignoreCase, int srcoffset, String dest, intdestoffset,
intlen): Another variation of regionMatches method with the extra boolean argument to
specify whether the comparison is case sensitive or case insensitive.
42. byte[] getBytes(String charsetName): It converts the String into sequence of bytes
using the specified charset encoding and returns the array of resulted bytes.
43. byte[] getBytes(): This method is similar to the above method it just uses the default
charset encoding for converting the string into sequence of bytes.
44. int length(): It returns the length of a String.
45. boolean matches(String regex): It checks whether the String is matching with the
specified regular expression regex.
46. intcodePointAt(int index):It is similar to the charAt method however it returns the
Unicode code point value of specified index rather than the character itself.

You might also like