U2 Java
U2 Java
UNIT-II, STRINGS
Q). What is a String? How to creating strings in java?
1. We can create a string just by assigning a group of characters to a string type variable:
String s="Hello";
2. We can create an object to String class by allocating memory using new operator. This is just
like creating an object to any class, like given here:
String s= new String("Hello");
Here, we are doing two things. First, we are creating object using new operator.
3. The third way of creating the strings is by converting the character arrays into strings. Let us
take a character type array: arr[] with some characters, as :
Now the String object 's' contains the string: "chairs". This means all the characters of the array
are copied into the string. If we do not want all the characters of the array into the string, then we
can also mention which characters we need, as:
Here, starting from 2nd character a total of 3 characters are copied into the strings.
Immutability of strings:
Mutable:- Mutable objects are those objects whose contents can be modified.
Immutable:- Immutable objects are those objects, once created cannot be modified.
And String class objects are immutable. Let us take a program to understand whether the String
objects are immutable or not.
class Test
{
public static void main(String arg[])
{
string s1="data";
string s2=new string("base");
s1=s1 + s2
System.out.println(s1);
}
}
Output:
C:> javac Test.java
C:\>java Test
Database
In java Strings are class objects and implemented using two classes, namely String and
StringBuffer. A java string is an instantiated object of the string class. A java string is not a
character array and not a NULL terminated. String may be declared and created as follows
Syntax:
String Methods:
The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks. Some most commonly used string methods.
Method Call Task Performed
s2 = s1.toLowerCase(); Converts the String s1 to all lowercase
s2 = s1.toUpperCase(); Converts the String s1 to all Uppercase
s2 = s1.replace(‘x’, ‘y’); Replace all appearances of x with y
s2 = s1.trim(); Remove white spaces at the beginning and
end of String s1
s1.equals(s2) Returns ‘true‘ if s1 is equal to s2
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.replace('I', 'i'));
System.out.println(s1.trim());
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.length());
System.out.println(s1.charAt(3));
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s1.concat(s2));
System.out.println(s2.substring(4));
System.out.println(s2.substring(0,6));
System.out.println(s2.startsWith(" "));
System.out.println(s2.endsWith(" "));
}
Output:
StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Method Task
s1.setCharAt(n, ‘x‘) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n, s2) Inserts the string s2 at the position n of the string s1
In java we can’t use (>,<,>=,<=) symbols for string comparison, We can compare String in Java on
the basis of content and reference. It is used in authentication.
1. equals() Method
2. Using == Operator
3. compareTo() Method
1) equals() Method
The String class equals() method compares the original content of the string. It compares values of
string for equality. String class provides the following two methods:
Teststringcomparison1.java
class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Virat";
String s2="Virat";
String s3=new String("Virat");
String s4="Kohli";
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //true
System.out.println(s1.equals(s4)); //false
}
}
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
2) == operator
eststringcomparison3.java
class Teststringcomparison3
{
public static void main(String args[])
{
String s1="Virat";
String s2="Virat";
String s3=new String("Virat");
System.out.println(s1==s2); //true (because both refer to same instance)
System.out.println(s1==s3); //false(because s3 refers to instance )
}
}
3) compareTo() method
The String class 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.
Teststringcomparison4.java
class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Virat";
String s2="Virat";
String s3="Kohli";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
}
}
Introduction to OOPs
Object-Oriented Programming
Definition:
Object-Oriented Programming is an approach that provides a way of modularizing programs
by creating partitioned memory area for both data and methods that can be used as
templates for creating copies of such modules on demand.
Object-Oriented Paradigm
The major objective of Object-Oriented approach is to eliminate some of the Drawbacks
encountered in the Procedural approach. OOP treats data as critical element in the program
development and does not allow the data to flow freely around the system. “It ties data more
closely to the methods that operate on it and protects it from accidental modification from
outside functions”.
The data of an object can be accessed only by the methods associated with the object. However
methods of one object can access the methods of other objects.
OOP allows us to decompose a problem into a number of entities called Objects. The
combination of data and methods make up an object.
1. Object
2. Class
3. Data Abstraction and Data Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing
1. Object
Objects are the real word entity (or) runtime entities in an object-oriented system. Objects are
closely matched with real world objects. Object may represent a person (or) a place, (or) table
of data (or) any item that can be handled by program. In order to store the data for the data
members of the class, we must create an object.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Definitions of an Object
Instance of a class is known as an object.
Class variable is known as an object.
Real world entities are called as Objects.
The following figure is the representation of an object
Object: student
Data:
name;
regdno;
Methods:
marks();
total();
avg();
result();
2. Class
“Collection of objects is called class”. It is a logical entity. A class is model for an object, and it is
a blue print of an object.
Once class has been defined, we can create any number of objects belongs to that class. Each
class is associated with data and methods.
For example mango, apple and banana are objects of fruit class. The syntax used to create
object is no different than the syntax used to create an integer object in C.
If fruit has been defined as a class, then the statement
fruit mango; // will create an object mango belonging to the class fruit.
Note: Any JAVA program can be developed with respect to Class only i.e., without Class there
is no JAVA program.
(Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and methods that operate on these attributes)
Ex:- While driving a car, you don’t have to concern with its internal working details, here we
need to concern about the parts like Steering, wheels, accelerators, Breaks, etc.
Data Encapsulation
The wrapping up (Combining) of data and methods into a single unit is known as
Encapsulation. Encapsulation is the most important feature of a class.
The data is not accessible to the outside world, but this Encapsulation provides direct access to
data. By this direct access the program is called data hiding or information hiding.
AKNU
COURSES
COLLEGE-2 COLLEGE-3
COLLEGE-1
COURSES COURSES
COURSES
UG PG UG PG UG PG
COURSES COURSES COURSES COURSE COURSE COURSES
S S
Fig. Inheritance
5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, it means the
ability to take more than one form is called Polymorphism.
The word Polymorphism means combining the two words i.e Poly & Morphism, poly means
many, morphism means availability.
For example, an operation may exhibit different behavior in different instances. The behavior
depends upon the types of data used in the operation. It supports two concepts.
a. Operator Overloading:
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading i.e. a single operator can perform different operations.
Ex. If the operands are two numbers then the operator is sum i.e., 2 + 3= 5.
If the operands are strings then the operator is concatenation.
b. Function Overloading:
A single function name is used to perform different types of tasks is known as function
overloading. The following is an example for polymorphism concept.
Fig. Polymorphism
6. Dynamic Binding
Binding refers if the code is associated with class function, we can’t identify that until the code
has been executed in run time, it is also called Dynamic binding. It is associated with the
polymorphism and inheritance.
7. Message Passing
The OOP’s consists of a set of objects that communicate with each other. Objects
communicate with one to another by sending and receiving information.
Exchanging the data between multiple objects is known as Message Passing. Objects
communicate with one another by sending and receiving information much the same way as
people pass message to one another.
Applications of OOP
OOPS applications are very important because of it is used in many areas like windows has
a more popular application in the OOPS. It is designed by interface with oops. The number of
windows systems developed by oops technique, like business system and commercial systems, etc
The following are some of areas of Object Oriented Programming
Real-Time systems
Simulation and modeling
Object oriented databases
Hypertext, hypermedia and expert text.
Parallel programming.
AI and expert systems.
Designing supports
Cam//Cad
Neural networks and parallel programming.
Decision support and office automation systems.
7. If size of the problem is small, POP 7. If the size of the problem is big, OOP
is preferred. is preferred.
8. In POP overloading is not possible 8. In OOP overloading is possible
9. POP does not have hiding 9. OOP has hiding security, so it is a
security, so it is less security highly secured
1. Procedural programming mainly focuses on procedures (or) functions. Less attention is given
to the data.
2. The data and functions are separate from each other.
3. Global data is freely moving and is shared among various functions. Thus, it becomes difficult
for programmers to identify and fix issues in a program that originate due to incorrect data
handling.
4. Changes in data types need to be carried out manually all over the program and in the
functions using the same data type.
5. Limited and difficult code reusability.
6. It does not model real-world entities (e.g., car, table, bank account, loan) very well where we
as a human being, perceive everything as an object.
7. The procedural programming approach does not work well for large and complex systems.
Classes, Objects
1. Defining a Class
“The process of binding the ‘data members’ and ‘member functions’ into a single unit is
called as a class”. In other words a class is a user defined data type. Once the class type has
been defined, we can create “variables” of that type. In java these variables are termed as
instances of class, which are the actual objects.
The basic form of a class definition is as follows;
[fields declaration;]
[methods declaration]
}
Here, sub_classname and super_clsname are any valid java identifiers. The keyword extends
indicates that the properties of the super_classname class are extended to the sub_classname
class. This concept is called as Inheritance.
Everything inside the square brackets is optional. This means that the following would be a
valid class definition.
class <class-name>
{
Here, the body of the class is empty; this does not contain any properties and therefore cannot
do anything.
We can declare the instance variables exactly the same way as we declare the local variables.
Syntax:
type < variable1,…… >
Example:
class Rectangle
{
int length; // Instance variable declaration
int width; // Instance variable declaration
}
The class Rectangle contains two integer type instance variables (length, width). Here, these
variables are only declared and therefore no storage space has been created in the memory.
Instance variables are also known as Member Variables.
(Note: In class we will have many numbers of variables and methods. Instance variables and methods in classes are accessible
by all the methods in the class but a method cannot access the variables declared in other methods.
Example:
class Check
{
int x;
void method1()
{
int y;
x=10; //legal
y=x; //legal
}
void method2()
{
int z;
x=20; //legal
z=10; //legal
y=5; //illegal
method1(); //legal
}
} )
OBJECT
1. Creating of an Object:
Object is a real word entity. “An instance of a class is called as an Object”. An object in java
is a block of memory that contains space to store all the member variables. Crating an
object is also referred to as Instantiating an object.
Objects in java are created using the new operator. The new operator creates an object for
the specified class and returns a reference to that object.
Here is an example of creating an object of type Rectangle.
The first statement declares a variable to hold the object reference(R1) and the second
one actually creates an object and assigns the object reference to the variable R1. The
variable R1 is now an object of the Rectangle class. Both statements can be combined
into one as shown below.
Rectangle R1 = new Rectangle();
The method Rectangle( ) is the Default Constructor of the class. We can create any
number of objects of Rectangle.
Example:
Each object has its own copy of the instance variable of its class. This means if any changes in
variables of one object that cannot effect on the other variables.
It is also possible to create two or more references to the same object as shown in below.
1. Here, object_name is the name of the object and variable_name is the name of the
instance variable inside the object.
3. parameter-list is separated by comma, and that must match in type and number with
the parameter list of the method name declared in the class.
The instance variables of the Rectangle class may be accessed and assigned values as
follows:
R1.length = 10;
R1.width = 20;
R2.length = 30;
R2.width = 40;
Note that the two objects R1 and R2 store different values as shown below:
In our case getData() method can be used to do this. We can call this getData() method by
using objects R1/R2 as follows:
R1.getData(1,2); // calls getData method and pass values 1, 2 to parameters x, y of the method getData
R2.getData(10,20);//calls getData method and pass values 10, 20 to parameters x, y of the method getData
The following is the program that illustrates the concepts discussed so far.
import java.lang.*;
class Rectangle // Declaration of class
{
int len, wid; // Declaration of instance variables
Constructors in Java
A constructor in Java is similar to a method, which is invoked when an object of the class is
created. Unlike Java methods, a constructor has the same name as that of the class and does not
have any return type.
For example,
Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return
type.
It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
class Main
{
private String name;
Main() // constructor
{
System.out.println("Constructor Called:");
name = "Programiz";
}
Output:
Constructor Called:
The name is Programiz
<class_name>
()
{
}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
//Java Program to create and call a default constructor
class Bike
{
Bike() //creating a default constructor
{
System.out.println("Bike is created");
}
public static void main(String args[]) //main method
{
Bike1 b=new Bike1(); //calling a default constructor
}
}
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Main
{
String lang;
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
3) They are arranged in a way that each constructor performs a different task.
4) They are differentiated by the compiler by the number of parameters in the list and
their types.
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Examplel: A program to initialize the Person class instance variables in Demo class.
//Initializing the instance variables
class Person
{
public String name; //public Instance variable
void disp()
{
System.out.println("Hello lam " + name);
System.out.println("My age is " + age);
}
Output:
Hello lam Raju
My age is 5
The access modifiers in Java specify 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.
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.
There are many differences between constructors and methods. They are given below.
Methods in JAVA
Methods must be declared inside the body of the class but immediately after the declaration of
instance variables.
Declaration:
Here, method name represents the name given to the method. After the method name, we
write some variables in the simple braces. These variables are called parameters. Method
parameters are useful to receive data from outside into the method.
Example
int sqrt (int num)
Here, sqrt is the method name, num is method parameter that represents that this method
accepts a int type value.
2. Method Body:
Below the method header, we should write the method body Method body consists of a group
of statements which contains logic to perform the task. Method body can be written in the
following format:
int method_name(parameter_list)
{
//statements;
}
For example, we want to write a method that calculates sum of two numbers. It may contain
the body, as shown here:
int c = a + b;
System.out.println("Sum of two = "+c);
}
If a method returns some value, then a return statement should be written within the body of
the method, as :
return x; // return x value
Program: Write a program for a method with two parameters and return type.
class Sample
{
int sum(int num1, int num2)
{
int res=num1 + num2;
return res; //return result
}
}
class Methods
{
public static void main(String args[])
{
Sample s = new Sample();
int x=s.sum (10, 22);
System.out.println("Sum="+x);
}
}
Output:
C:\>javac Methods.java
C:\> java Methods
Static Members
The variables and methods in the class are called as instance variables and instance methods.
This is because every time the class is instantiated, a new copy of each of them is created.
They are accessed using the objects (with dot operator).
Let us assume that we want to define a member that is common to all the objects and
accessed without using particular object.
i.e. the member belongs to the class as a whole rather than the objects created from the class.
Such members can be defined as follows:
The members that are declared with the keyword static are called as static members. Since
these members are associated with the class itself rather than individual objects, the static
variables and static methods are often referred to a class variables and class methods.
Static variable:
static method:
Syntax :
<class-name>.<variable-name>;
<class-name>.<method-name>;.
Note: main () method is static, since it must be accessible for an application to run, before any
instantiation takes place.
The keyword 'this': 'this' is a keyword that refers to the object of the class where it is used. In
other words, 'this' refers to the object of the present class. Generally, we write instance
variables, constructors and methods in a class.
All these members are referenced by 'this'. When an object is created to a class, a default
reference is also created internally to the object, as shown in the Figure. This default reference
is nothing but 'this'. So 'this' can refer to all the things of the present object.
Instance methods: Instance methods are the methods which act upon the instance
variables. To call the instance methods, object is needed, since the instance variables are
contained in the object. We call the instance methods by using objectname.methodname().
The specialty of instance methods is that they can access not only instance variables but
also static variables directly.
Accessor methods are the methods that simply access or read the instance variabiles. They
do not modify the instance variables.
Mutator methods not only access the instance variables but also modify them.
class Person
{
private String name;
private int age;
public void setName(String name) //mutator methods to store data
{
this.name =name;
}
public void setAge(int age)
{
this.age= age;
}
public void setAge(int age)
{
this.age=age;
}
public String getName() // Accessor metods to read data
{
return name;
}
public int getAge()
{
return age();
}
}
class Methhods
{
public static void main(String args[])
{
Person p1=new Person();
p1.setName(“Raju”);
p1.setAge(20);
System.out.prinntln(“Name=”+p1.getName());
System.out.prinntln(“Age=”+p1.getAge());
}
}
Output:
Primitive data types (or) fundamental data types represent single entities (or) single values.
For example, char, byte, short, int, long, float, double and boolean are called primitive data
types, because they store single values. They are passed to methods by value.
This means when we pass primitive data types to methods, a copy of those will be passed
to methods. Therefore, any changes made to them inside the method will not affect them
outside the method. In the following program, we pass two integer numbers 10 and 20 to
the swap method. Let us display the output to know whether they are interchanged or not.
Program:
class check
{
vold swap (int n1, int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
}
}
class PassPrimitive
{
public static void main(String args[])
{
int n1= 10, n2=20;
check ck= new check ();
System.out.println(n1+ " " +n2);
ck.swap(n1, n2);
System.out.println(n1+" " +n2);
}
}
Output:
C> javac PassPrimitive.java
C:>java PassPrimitive
10 20
10 20
class Check
{
value swap(Employee obj)
{
int temp;
temp=obj.id1;
obj.id1 = obj.id2;
obj.id2=temp;
}
}
class PassObjects
{
public static void main(String args[])
{
Employee obj1 = new Employee(10, 20);
Check obj = new check();
System.out.println(obj1.id1+""+obj1.id2);
obj.swap(obj1);
System.out.println(obj1.id 1+"\t"+obj1.id2);
}
}
Output:
C: javac Pass Objects.java
Objects Pass Objects
10 20
2019
Just like the objects are passed to methods, it is also Possible to pass arrays to methods and
return arrays from methods. In this case, an array name should be understood as an object
reference. For example,
int [] myMethod(int arr[])
This is the way, we can pass a one dimensional array 'arr' to 'myMethod()'. We can also
return a one dimensional array of int type as shown in the preceeding statement.
int[] [] myMethod(int arr[][])
Here, we are passing and returning a two dimensional array of int type.
Example:
class Array
{
public int[] sortArr (int a [], int len)
{
for(i=0; i<len; i++)
for (j=i+1; j<len;j++)
{
if (a[i]>a[j])
{
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
return a;
}
public static void main(String args[])
{
int a[]={10, 40, 30, 20, 50);
int b[]=obj.sortln(a,a.lengt);
System.out.println("sorted array elements are");
for(int i=0;i<b.length;i++)
System.out.println(b[i] +’’);
}
}
Output:
sorted array elements are
10 20 30 40 50
A static block is a block of statement declared as “static”, some thing like tis:
static
{
Statement;
}
JVM execute a static block on a highest priority basis. This means JVM first goes to static
block even before it looks for the main() method in the program.
Example:
Class Test
{
Static
{
System.out.println(“Static block”);
}
public static void main(String args[])
{
System.out.println(“Static method”);
}
}
Output:
class Recursion
{
static long factorial(int num)
{
long result;
if (num==1)
return 1;
result =factorial (num-1)*num;
return result;
}
public static void main(String args[])
{
System.out.println("Factorial of 5:");
System.out.println(Recursion.factorial(5));
}
}
Output:
C:\>javac Recursion.java
C:\>java Recursion
Factorial of 5;
120
A factory method is a method that creates and returns an object to the class to which
it belongs. A single factory method replaces several constructors in the class by
accepting different options from the user, while creating the object.
class Circle
{
public static void main(String arg[])
{
final double PI = (double)22/7;
double r= 15.5; //radius
double area = Pl*r*r;
System.out.println("Area = " + area);
}
}
Output:
C:>javac Circle.java
C:\> java Circle
Area-755.0714285714286
Inheritance in Java
Inheritance in Java
It 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.
Parent (Properties)
Fig: Inheritance
The class which is giving members (variables and methods) to some other class is
known as base class / super class / parent class.
The class which is retrieving or obtaining members (variables and methods) is known
as derived class / sub class / child class.
The inheritance allows subclasses to inherit all the variables and methods of their
parent classes. A Derived class contains its own properties (members) plus base
class properties (members).
Advantages of Inheritance
Syntax for INHERITING the features from base class to derived class:
The keyword extends signifies that the properties of the super_classname are
extended to the sub_classname.
The subclass will now contain its own variables and methods as well those of
the super class.
This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying it and also improves functionality of
derived class.
1. Single Inheritance
In Single Inheritance single base class is derived to a single derived class. If one child
class is inheriting the properties of the parent class without any intermediate class,
then it is called as “Single Inheritance”.
A subclass acquires the properties from the super class is also called as “Single
inheritance”. For example C2 class is derived from C1 class; Now C2 access all the
properties of C1 and itself. It is shown in below.
class c1
{
---------
}
class c2 extends c1
{
---------
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
2. Multilevel Inheritance
Multilevel Inheritance contains one base class and one derived class, and multiple
intermediate base classes.
For example C2 class is derived from C1, C3 class is derived C2, and C4 class is
derived C3; Now C2 access C1 class members and itself only, C3 access C2 and C1
class members and itself only, and C4 can access C3,C2,C1class members and itself
only. It is shown in below.
Example:
class c1
class Animal {
---------
{
---------
void eat() }
{ class c2 extends c1
System.out.println("eating..."); {
} ---------
---------
} }
class c3 extends c2
class Dog extends Animal{ {
void bark() ---------
{ ---------
}
System.out.println("barking..."); class c4 extends c3
} {
} ---------
---------
class BabyDog extends Dog }
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
3. Hierarchical Inheritance
Hierarchical Inheritance contains a single base class and multiple derived classes. In
hierarchical inheritance multiple subclasses acquire the properties of only single
super class, it is also called as hierarchical inheritance.
For example C2, C3, C4, classes are derived from C1 class; Now C2, C3, C4 classes can
access C1 class members and itself only. It is shown in below.
Syntax:
class c1
{
---------
---------
}
class c2 extends c1
{
---------
---------
}
class c3 extends c1
{
---------
---------
}
class c4 extends c1
{
---------
---------
}
Example:
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{System.out.println("meowing...");}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
4. Multiple Inheritance
Multiple Inheritance contains multiple base classes and a single derived class. For
example C4 class is derived from C1, C2, and C3 Base classes; Now C4 can access C1,
C2, C3 members and itself. It is shown in below.
Super keyword
Subclass Constructor (‘super’ keyword)
A Subclass constructor is used to construct the instance variables of both the subclass
and the super class. The subclass constructor uses the keyword super to invoke the
constructor method of the super class. The super keyword is used subject to the
following conditions.
The Protected Specifier: The private members of the super class are not available to sub
classes directly. But sometimes, there may be a need to access the data of super class in the
sub class.
For this purpose, protected specifier is used. Protected is commonly used in super class to
make the members of the super class available directly in its sub classes.
Example: Program to understand private members are not accessible in subclass, but
protected members are available in sub class.
class Access
{
private int a;
protected int b;
}
class Test
{
public static void main(String args[])
{
Subs= new Sub ();
s.get();
}
}
Output: