0% found this document useful (0 votes)
7 views

java unit 2 khader sir

The document provides an overview of inheritance in Java, explaining the concepts of superclasses, subclasses, and access specifiers. It covers types of inheritance, constructors, method overriding, abstract classes, and the use of the final keyword. Additionally, it discusses string handling, string manipulation methods, and the StringTokenizer class for tokenizing strings.

Uploaded by

Srinu Devi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
7 views

java unit 2 khader sir

The document provides an overview of inheritance in Java, explaining the concepts of superclasses, subclasses, and access specifiers. It covers types of inheritance, constructors, method overriding, abstract classes, and the use of the final keyword. Additionally, it discusses string handling, string manipulation methods, and the StringTokenizer class for tokenizing strings.

Uploaded by

Srinu Devi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 11
2 2 KV ACADEMY 9966648277 INHERITANCE ee ‘a mechanism by which one class is derived from other class. The class from which other class is derived is called super class and the class which derives the super class is called sub class. Inheritance c a powerful mechanism for reusing the code. The java language uses the extends keyword to implement inheritance. A sub-class is defined in the following form. class sub-class extends super-classname /Ioody of the class } The “extends” keyword indicates that the properties of the superclass are extended to the subclass. The subclass then contains its own variables and methods as well as those of superclass. MEMBER ACCESS RULES :- An “access specifier" is used to specify how a member can be accessed . Java's access specifiers are: public , private & protected. In addition to these three if no specifier is used, it result in default. A private data member cannot be inherited in the subclass. A public and protected data members are inherited in the subclass. When no modifier is used, it results in default. default members are also inherited in the subclass. SUPER :- Super is a keyword that is used for two purposes. First it is used to call the constructor of its immediate super class and the second is that it is used to access the member of a superclass that has been hidden by a member of subclass. Using super to call super class constructor: - A subclass can call a constructor method of its superclass by the use of “super”. Its general form is: super(parameters-list); The parameter-list is specifies any parameters needed by the constructor in the superclass. super() must always be the first statement inside the Scanned with CamScanner re i, | g ve KV ACADEMY es Ri | oe constructor of subclass. When a subclass calls super() , it is callin, é # constructor of its immediate superclass. eg j 3 Using super to access superclass member: - ' os he same name of the member present in super Tf a subclass has a member with ¢ A \ 4 erclass member class, then the superclass member is hidden. Te 33 that superc! super can be used, It has the following form super.member ‘0 acce: Example :- TYPES OF INHERITANCE:- Java supports three types of inheritance. They are : is only one base class and only one i. Single inheritance: In single inheritance there derived class. Class -A Class -B Hierarchical inheritance:- In hierarchical inheritance, there is only one base class but many derived class. Class -A. Class-B Class-C Class- D iii. Multilevel inheritance: In multilevel inheritance , a class is derived from already derived class. Class-A t Class- B i Class-C Scanned with CamScanner KV ACADEMY 9966648277 jother type of inheritance called multiple inheritance also exists. But java does not ‘support multiple inheritance directly. It supports multiple inheritance through interfaces. Constructors in Inheritance:- In inheritance, each class can have its own constructor. So when the object for the lowest derived class is created the constructors of all the base classes is executed. The constructors are called in order of derivation that is from superclass to subclass. If super() is used in constructor, then the respective constructor with that arguments are called. If super() is not called , then the default or parameterless constructor of each super class is called. Example - class A{ Al) { System.out printin( “class A”); } class B extends A { Bt) { } System.out.printin(“class 8”); } class C extends B { ct) { system.out.printin(“class C”); class test { public static void main(String args{}) { Cx= new C(); } } ‘The output from the above program is : Class A Scanned with CamScanner KV ACADEMY my é Class B Class¢ we METHOD OVERRIDING:- aa When a method in the subclass has the same name and type signature as a method inn? & 9 ; © a8 Super class, then the method in the subclass is sald to override the method in superclass, « The method defined by the superclass is hidden. To access the superclass version of an * , a overridden function, we have to use super. Example - class Base { int a; Base{int x) a=x; } void show () { System.out.printin("a=" ta); } ) class Derived extends Base intb; Derived(int x, int y) { super(x); b=b; } | void show() super.show(); System.out.printin(“b= "+b); } “. } class test Public static void main(String args[]) Derived obj =new Derived(1,2,8); obj.show(); Scanned with CamScanner KV ACADEMY 9966649277 AABSTRACT.CLASSES :- ‘An abstract class contains methods that are not defined, Such methods has to be over ridden or implemented by the class that extends this abstract class. To make a method to be over ridden by subclass, it must be preceded with “abstract” modifier. To declare an abstract method following syntax is used : abstract return-type method-name (parameter-list); To create aabstract class, the class must be preceded by “abstract” modifier, Its general form is: abstract class class-name { //body of the class // body can contain both abstract and non-abstract methods, } Y An abstract class cannot be used to create objects. USING FINAL :-“final” is a keyword. Itis used for three purposes, |. Creating named constants :- The keyword “final” general form is : ) finaldata-type variable-name = value; can be used to create constants. Its The variables with final modifier must be initialized to some constant. Il. Prevent Over riding:- To prevent a method from being over ridden , specify a “final” modifier at the start of its declaration. Methods declared as final cannot be overridden. Syntax : final return-type method-name (parameters-list) { // body of the method } Ill Prevent Inheritance:- Sometimes it is required to prevent a class from being inherited. In such cases, precede the class declaration with “final”. Syntax : final class class-name { [body of the class } Declaring a class as “final ” implicitly declares all of its methods as final. Scanned with CamScanner oy 2 g § KV ACADEMY g mF Foy OBJECT CLASS:- 2 Object class isa special class in java Al other classes in java are subclasses of object clay, That is, object is a superclass of all other classes “object” consists of some methods , which & ~ means that they are available in every object. some of the object class methods clone(), \ equals(), getClass() and toString() DYNAMIC POLYMORPHISIM: A function or method can be over ridden by any subclass. The method that is to be called, that is superclass method or subclass method is decided at Tuntime. This is called as dynamic polymorphism or runtime polymorphism. Java implements runtime polymorphism using dynamic method dispatch as follows: ‘Method in class 1 Method in class 2 Super-class dispatcher reference ‘Method in class n The superclass reference is examined by the dispatcher for the type of the object it is referring to at run-time. Depending on the type of object being referred by the superclass {| reference the dispatcher decides which version of method is to be called .Itis also called as | late binding because the decision is taken late at runtime rather than at compile time. Example :- classBase { void display () { ‘System.out.printIn(“base”); } } class Derived extends Base { void display () { —$——$—$—$—$<<$<_$<_$_—$—_$—_$—_$_$—_ 1 Scanned with CamScanner a % : ) KV ACADEMY 9966648277 g gyster.out-printin("derived”}; %, ae} } qasstest : public static void main(String args{]) { Base b= new Base(); Derived d=new Derived(); Base 1} r.display(); r=d; r.display(); } i Output Base Derived BENEFITS OF INHERITANCE: ‘a. Software reusability: When some behavior is to implemented, and if that behavior is already present in some other class, then it need not be re-written with the concept of inheritance, the existing behavior can be re- used. b. Increased relia The code that is re-used is tested previously and is mostly free of bugs. Thus inheritance increases reliability. c. Code sharing: The code developed by one user or for one project can be re-used by another user or some other project. d. Information hiding:- A programmer who re-uses the class by inheriting is does not need to know the details of the class and its implementation. Thus the details of the information is hidden from the user who re-uses it. COSTS OF INHERITANCE: Execution speed :-The inherited methods are slower in execution as it requires extra work like solving conflicts of over-ridden methods. Progtam size :- The program may or may not use all the methods of the inherited class. But every object of subclass, contains the complete super class. So this increases the overall program size. STRING HANDLING: Scanned with CamScanner 1 KV ACADEMY 9954. § j trings are handleg® & String is a sequence of characters, In java, string v6 two classes, They are the string class and the StringBuffer clas Both the classes are from Java.lang package. The difference between \ the two classes is that, the strings created by String class are \ immutable whereas strings created by StringBuffer class is not immutable, By immutable, reassigned with STRING CLass: In java, a string class is used to create and handle the sequence of characters. it has several ing objects. Some of them are as follows: |. String() ——> Itcreates an Ul. String(char chf]) constructions for creating and initializing str empty string of length zero. ——> This creates a string and initialize 's it by the array of characters, Example: chararr[]={‘a!,'bi,!c!,1ary; String s= new String(arr) ;//s will contain “abcd” Il. String(String obj) creates a string from the given string object. Example: String sl=new String("Hello”) ; String s2=new String(s1) ; STRING MANIPULATIONS: | ‘STRING MANIPULATIONS: String class provides many methods to manipulate strings. COMPARING STRINGS The objects of string can be compared by three methods: equals), equalsignoreCase() and compareTo(). The equals() method compares the contents of the object. Scanned with CamScanner KV ACADEMY 9966648277 iqualsignoreCase() method compares the contents of the string object but ignores the ‘he compareTo() method compares the two strings character-wise and returns an at value. If both the strings are same it returns 0. Otherwise it returns the difference of the ASCII characters where the strings differ. Example: // Program to illustrate comparison of strings public class ComparingString { public sti { String sl="Hello”; a String s2=new String("Hello”) ; string s3=new String(“hello”); atic void main(String args{]) out pprintIn(s14"equals”#s2#":"+s1 equals (82) ) out _printIn(sl+"equals”+s3+":”+s1.equals (3) )7 out _printIn(s1+"equalsignoreCase”+s3+”: "+51 .equalsIgnoreCase (53) ) 7 Tout _printIn(s1+"compareTo”+s2+":""+s1..compareTo(s2)) 7 out -print1n(s1+"compareTo"+s3+”:"+s1.compareTo(s3) ) 7 “out .printIn (s3+"compareTo"+s1+”":/"+s3.compareTo(s1) ) CHECKING CHARACTERS AND SUBSTRINGS IN A STRING: intindexOf(char ch) Returns-the index where the first “ch” is found in the string, Returns -1 if “ch” is not present. intindexOfstring tr) Returns_the index where the first “str” is found in the invoking string Returns -1 if “str” not present. Example: // Program to check the position of characters and substrings in a string. classStringPos public static void main(String args[{]) { String s="Once upon a time, a king”; System.out.println(“e is located at:"+s.indexOf( Se): system.out.printin(“last e is located At:"+s.lastIndexof(‘e’))7 system.out.println("x is located at:”+s.indexOf(‘x'))i system.out.printIn("time is located at:'+s.indexOf (“time”) ) + } Oy Scanned with CamScanner Ss fF KV ACADEMY 996¢ ee & EXTRACTING SUBSTRING: String subString(intindex)Returns the substring from the given index to the end. String substring(intfromindex,inttolndex)Returns-a substring from given “fromindex” to “tolndex"-1 Example: //Program to extract substrings from a string classsubstringDemo { public static void main(String args{]) { String s="Strings In java”; System.out.printin ("Substring from index6:’+s.subString(6)); System.out.println ("Substring from index 2 to8:"+S.subString(2,9)) i } SIZE OF THE STRING: int length() —> Returns the number of characters in the invoking string counts space also a character. LOCATING CHARACTER: char charAt(intpos) | —Returns the character at the index pos. ‘STRING-BUFFER: StringBuffer class is used to create mutable string objects. That is the string objects created by this class can be changed in the same memory location where it is stored. It has the following constructors: stringBuffer() ——> Creates an empty StringBuffer. > stringBuffer(int capacity) ——> Creates an empty StringBuffer with the given initial capacity. Default capacity is 16 stringBuffer(String str) ——>creates a StringBuffer to hold the given string and initialize it with the given string. intlength() ——> _ Returns the number of characters currently present in the string. intcapacity() Returns the number of characters that can be stored in the StringBuffer without requiring additional memory. Scanned with CamScanner pure 19966 NAIC KV ACADEMY 9966648277 charAt(intpos) ——> Returns the character present at that index pos. | void reverse() ——> Reverse the character in the StringBuffer. String subStringtint from) 5 Returns a substring from the index from to the end of the string. String subString(int from, {nt to) > Returns a substring from the index “from” to "to" <1. et STRING TOKENIZI as A stringTokenizer class is used to break down a string into parts called tokens. The process of converting a string into a token is called as tokenization. The string is broken depending on the delimiters. The default delimiter used for tokenize a string are white spaces characters such as space, tab, new-line etc. Other characters can also be used as delimiters. The String Tokenizer class has the following constructors: StringTokenizer(String s) It tokenizes the string “s” with the default delimiters. StringTokenizer(String s, Stringdelim) _ It tokenizes the string “s” with the delimiter “delim”. StringTokenizer(String s, String delim, Boolean delimAsToken)It tokenizes the string “s” with the delimiters “delim”. The delimiter used is also included as a token if the third argument is true. Otherwise, it is same as the second constructor. The StringTokenizers class has the following methods: intcountTokens()_ Returns the number of tokens present in stringTokenizer object. booleanhasMoreTokens() ——Returns true if there are one or more tokens available on the string. stringnextToken() —Returns the next token as a string. xample: // Program to count the numbers of words in a string and print them. public class Demo{ public static void main(String args{]) { String str="This is a java program to demonstrate StringTokenizer”; StringTokenizerst=new StringTokenizer(str); System. out printin("Number of words in the string are:”+st.countTokens()); System.out.printin("The words are:”); while(st-hasMoreTokens()) { System.out.printin(st.nextToken()); } Scanned with CamScanner

You might also like