The document discusses several key object-oriented programming concepts in Java including access specifiers (public, private, protected), static methods and variables, inheritance, abstract classes, method overriding, and packages. It provides examples and explanations of how each concept works in Java.
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0 ratings0% found this document useful (0 votes)
88 views39 pages
Object Oriented Concepts Through Java
The document discusses several key object-oriented programming concepts in Java including access specifiers (public, private, protected), static methods and variables, inheritance, abstract classes, method overriding, and packages. It provides examples and explanations of how each concept works in Java.
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 39
Object Oriented Concepts
and Programming through
JAVA Access Specifiers • Java’s access specifiers are – public, – private, – Protected and – a default access level. • When a member of a class is specified as public, then that member can be accessed by any other code. • When a member of a class is specified as private, then that member can only be accessed by other members of its class. • That’s why main( ) has always been preceded by the public specifier. • It is called by code that is outside the program—that is, by the Java run-time system. Access Specifiers • When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. • Protected used when inheritance is there. • Example Understanding static • Sometimes you want to define a class member that will be used independently of any object of that class. • It is possible to create a member that can be used by itself, without reference to a specific instance. • To create such a member, precede its declaration with the keyword static. • When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. • You can declare both methods and variables to be static. • The most common example of a static member is main( ). • main( ) is declared as static because it must be called before any objects exist. Cont… • Instance variables declared as static are, essentially, global variables. • When objects of its class are declared, no copy of a static variable is made. • Instead, all instances of the class share the same static variable. • Methods declared as static have several restrictions: – They can only call other static methods. – They must only access static data. – They cannot refer to this or super in any way. Inheritance • It allows the creation of hierarchical classifications. • you can create a general class that defines traits or properties common to a set of related items. • This class can then be inherited by other, more specific classes, each adding those things that are unique to it. • In the terminology of Java, a class that is inherited is called a superclass. • The class that does the inheriting is called a subclass. • A subclass is a specialized version of a superclass. • It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements. Cont… • To inherit a class, we incorporate the definition of one class into another by using the extends keyword. • class A{} • class B extends A{} • Example • Superclass can be used as a complete independent, stand-alone class. • A subclass can be a superclass for another subclass. • The general form class subclass-name extends superclass-name { // body of class } Member Access and Inheritance • A subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. Using super() • There will be times when you will want to create a superclass that keeps the details of its implementation to itself. • That is, that keeps its data members private. • Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. • super has two general forms. – The first calls the superclass’ constructor. – The second is used to access a member of the superclass that has been hidden by a member of a subclass. Cont… • Using super to Call Superclass Constructors: super(parameter-list); • super( ) must always be the first statement executed inside a subclass’ constructor. • When a subclass calls super( ), it is calling the constructor of its immediate superclass. • Thus, super( ) always refers to the superclass immediately above the calling class. • A Second Use for super : – super.member • This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Constructor calling sequence • In a class hierarchy, constructors are called in order of derivation, from superclass to subclass. • Since super( ) must be the first statement executed in a subclass’ constructor, this order is the same whether or not super( ) is used. • If super( ) is not used, then the default or parameterless constructor of each superclass will be executed. Method Overriding • When a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. • When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. • If you wish to access the superclass version of an overridden function, you can do so by using super. • Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. • Overridden methods allow Java to support run-time polymorphism. Cont… • Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods. • Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism. Using Abstract Classes • Sometime you want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. • Sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. • Such a class determines the nature of the methods that the subclasses must implement. • One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. • Figure class area() method • You may have methods which must be overridden by the subclass in order for the subclass to have any meaning. Cont… • Sometime you want some way to ensure that a subclass does, indeed, override all necessary methods. Java’s solution to this problem is the abstract method. • You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. • These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. • Thus, a subclass must override them—it cannot simply use the version defined in the superclass. • To declare an abstract method, use this general form: abstract type name(parameter-list); Cont… • Any class that contains one or more abstract methods must also be declared abstract. • To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. • There can be no objects of an abstract class. • That is, an abstract class cannot be directly instantiated with the new operator. • Such objects would be useless, because an abstract class is not fully defined. • Also, you cannot declare abstract constructors, or abstract static methods. • Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. Using final with Inheritance • Using final to Prevent Overriding – 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. – Early and late binding • Using final to Prevent Inheritance – Sometimes you will want to prevent a class from being inherited. – To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. – It is illegal to declare a class as both abstract and final Packages • Packages are containers for classes that are used to keep the class name space compartmentalized. • For example, a package allows you to create a class named List, which you can store in your own package without concern that it will collide with some other class named List stored elsewhere. • Packages are stored in a hierarchical manner and are explicitly imported into new class definitions. • Name collision without packages. • Java provides a mechanism for partitioning the class name space into more manageable chunks. Cont… • This mechanism is the package. The package is both a naming and a visibility control mechanism. • You can define classes inside a package that are not accessible by code outside that package. • You can also define class members that are only exposed to other members of the same package. • This allows your classes to have intimate knowledge of each other, but not expose that knowledge to the rest of the world. String Class • Every string you create is actually an object of type String. • Objects of type String are immutable; once a String object is created, its contents cannot be altered. • This may seem like a serious restriction, it is not, for two reasons: – If you need to change a string, you can always create a new one that contains the modifications. – Java defines a peer class of String, called StringBuffer, which allows strings to be altered, so all of the normal string manipulations are still available in Java. • String myString = "this is a test"; • System.out.println(myString); Cont… • Operator for String objects: +. It is used to concatenate two strings. • String myString = "I" + " like " + "Java."; • The String Constructors – String s = new String(); – String(char chars[ ]) – String(char chars[ ], int startIndex, int numChars) – String(String strObj) – String(byte asciiChars[ ]) – String(byte asciiChars[ ], int startIndex, int numChars) Cont… • The length of a string is the number of characters that it contains. • int length( ); is used to get length. char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); • String concatenation is done with various data types. String age = 9; String s = "He is " + age + " years old."; System.out.println(s); • What will be the output of following code? String s = "four: " + 2 + 2; System.out.println(s); Cont… • String Conversion and toString( ) – Java converts data into its string representation during concatenationby using overloaded versions of the string conversion method valueOf( ) defined by String. – valueOf( ) is overloaded for all the simple types and for type Object. – For objects, valueOf( ) calls the toString( ) method on the object. – Every class implements toString( ) because it is defined by Object. – General form is String toString( ); – Example of Box Class Cont… • Character Extraction – charAt( ) • Extract a single character from a string • char charAt(int where) • ch = "abc".charAt(1); – getChars( ) • To extract more than one character at a time • void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) – getBytes( ) • To stores the characters in an array of bytes. • byte[ ] getBytes( ) Cont… – toCharArray( ) • To convert all the characters in a String object into a character array • char[ ] toCharArray( ) Cont… • String Comparison • equals( ) and equalsIgnoreCase( ) – To compare two strings for equality, use equals( ). boolean equals(Object str) – It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. – To perform a comparison that ignores case differences, call equalsIgnoreCase( ). boolean equalsIgnoreCase(String str) Cont… String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; s1.equals(s2); s1.equals(s3); s1.equals(s4); s1.equalsIgnoreCase(s4); Cont… • regionMatches( ) – Compares a specific region inside a string with another specific region in another string. boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars) boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars) • startsWith( ) and endsWith( ) – The startsWith( ) method determines whether a given String begins with a specified string. – The endsWith( ) determines whether the String in question ends with a specified string. – Second form of startsWith() is boolean startsWith(String str, int startIndex) Cont… • equals( ) Versus == – the equals( ) method compares the characters inside a String object. – The == operator compares two object references to see whether they refer to the same instance. String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); Cont… • compareTo( ) – For sorting applications, you need to know which is less than, equal to, or greater than the next. – A string is less than another if it comes before the other in dictionary order. – int compareTo(String str) Value Meaning Less than zero The invoking string is less than str. Greater than zero The invoking string is greater than str. Zero The two strings are equal. • If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( ), Cont… • Searching Strings – indexOf( ) Searches for the first occurrence of a character or substring. – lastIndexOf( ) Searches for the last occurrence of a character or substring. – int indexOf(int ch) – int indexOf(String str) – int indexOf(int ch, int startIndex) – int indexOf(String str, int startIndex) Cont… • Modifying a String • substring( ) – You can extract a substring using substring( ). – String substring(int startIndex) – String substring(int startIndex, int endIndex) – result = org.substring(0, 7); • concat( ) – You can concatenate two strings using concat( ) – String concat(String str) • replace( ) – The replace( ) method replaces all occurrences of one character in the invoking string with another character. Cont… – String replace(char original, char replacement) – String s = "Hello".replace('l', 'w'); • trim( ) – The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. – String s = " Hello World ".trim(); – The trim( ) method is quite useful when you process user commands. Cont… • Data Conversion Using valueOf( ) – The valueOf( ) method converts data from its internal format into a human-readable form. – static String valueOf(double num) – static String valueOf(long num) – static String valueOf(Object ob) – static String valueOf(char chars[ ]) • Changing the Case of Characters – String toLowerCase( ) – String toUpperCase( ) Cont… • StringBuffer – String represents fixed-length, immutable character sequences. In contrast, – StringBuffer represents growable and writeable character sequences. – StringBuffer may have characters and substrings inserted in the middle or appended to the end. – StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. – StringBuffer( ) – StringBuffer(int size) – StringBuffer(String str) Cont… • int length( ) • int capacity( ) • void setLength(int len) – len value must be nonnegative. – If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. • char charAt(int where) • void setCharAt(int where, char ch) • getChars( ) – void getChars(int sourceStart, int sourceEnd, char target[ ],int targetStart) Cont… • append( ) – The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. – StringBuffer append(String str) – StringBuffer append(int num) – StringBuffer append(Object obj) • insert( ) – The insert( ) method inserts one string into another. – StringBuffer insert(int index, String str) – StringBuffer insert(int index, char ch) – StringBuffer insert(int index, Object obj) – StringBuffer sb = new StringBuffer("I Java!"); – sb.insert(2, "like "); Cont… • reverse( ) – StringBuffer reverse( ) – This method returns the reversed object on which it was called. • delete( ) and deleteCharAt( ) – StringBuffer delete(int startIndex, int endIndex) – StringBuffer deleteCharAt(int loc) • replace( ) – It replaces one set of characters with another set inside a StringBuffer object. – StringBuffer replace(int startIndex, int endIndex, String str) Cont… • substring( ) – Returns a portion of a StringBuffer. – String substring(int startIndex) – String substring(int startIndex, int endIndex)