Uploaded by Aakanksha Pundir

Inheritance in Java

advertisement
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Terms used in Inheritance
o
Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o
Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3.
//methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
1. class Employee{
2.
float salary=40000;
3. }
4. class Programmer extends Employee{
5.
int bonus=10000;
6.
public static void main(String args[]){
7.
Programmer p=new Programmer();
8.
System.out.println("Programmer salary is:"+p.salary);
9.
System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{
2. void eat()
3. {
4. System.out.println("eating...");}
5. }
6. class Dog extends Animal{
7. void bark()
8. {
9. System.out.println("barking...");}
10. }
11. class TestInheritance{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.bark();
15. d.eat();
16. }}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9.
public static void main(String args[]){
10.
C obj=new C();
11.
obj.msg();//Now which msg() method would be invoked?
12. }
13. }
String Handling
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence
interfaces.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant
pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Java String Example
StringExample.java
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Test it Now
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String objects s1,
s2, and s3 on console using println() method.
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
No.
Method
Description
1
char charAt(int index)
It returns char value for the particular in
2
int length()
It returns string length
3
static String format(String format, Object... args)
It returns a formatted string.
4
static String format(Locale l, String format, Object... args)
It returns formatted string with gi
locale.
5
String substring(int beginIndex)
It returns substring for given begin inde
6
String substring(int beginIndex, int endIndex)
It returns substring for given begin in
and end index.
7
boolean contains(CharSequence s)
It returns true or false after matching
sequence of char value.
8
static String join(CharSequence delimiter, CharSequence...
elements)
It returns a joined string.
9
static String join(CharSequence delimiter, Iterable<?
extends CharSequence> elements)
It returns a joined string.
10
boolean equals(Object another)
It checks the equality of string with
given object.
11
boolean isEmpty()
It checks if string is empty.
12
String concat(String str)
It concatenates the specified string.
13
String replace(char old, char new)
It replaces all occurrences of the speci
char value.
14
String replace(CharSequence old, CharSequence new)
It replaces all occurrences of the speci
CharSequence.
15
static String equalsIgnoreCase(String another)
It compares another string. It doesn't ch
case.
16
String[] split(String regex)
It returns a split string matching regex.
17
String[] split(String regex, int limit)
It returns a split string matching regex
limit.
18
String intern()
It returns an interned string.
19
int indexOf(int ch)
It returns the specified char value index
20
int indexOf(int ch, int fromIndex)
It returns the specified char value in
starting with given index.
21
int indexOf(String substring)
It returns the specified substring index.
22
int indexOf(String substring, int fromIndex)
It returns the specified substring in
starting with given index.
23
String toLowerCase()
It returns a string in lowercase.
24
String toLowerCase(Locale l)
It returns a string in lowercase us
specified locale.
25
String toUpperCase()
It returns a string in uppercase.
26
String toUpperCase(Locale l)
It returns a string in uppercase us
specified locale.
27
String trim()
It removes beginning and ending space
this string.
28
static String valueOf(int value)
It converts given type into string. It is
overloaded method.
Download