Super classes- sub classes –Protecters –

PackialathaVISTAS 6 views 86 slides Aug 31, 2025
Slide 1
Slide 1 of 86
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86

About This Presentation

Super classes- sub classes –Protected
members – constructors in sub classes- the Object
class – abstract classes and methods- final methods
and classes – Interfaces – defining an interface,
implementing interface, differences


Slide Content

UNIT - II INHERITANCE AND INTERFACES

Inheritance – Super classes- sub classes –Protected members – constructors in sub classes- the Object class – abstract classes and methods- final methods and classes – Interfaces – defining an interface, implementing interface, differences between classes and interfaces and extending interfaces – Object cloning -inner classes , ArrayLists – Strings

superclass subclass2 int d; subclass1 int c; void add(){} int a; int b; void test(){} int a; int b; int c; void test(){} void add(){} int a; int b; int d; void test(){} INHERITANCE IN JAVA - One class can inherit traits/properties of another class. - class that is inherited is called superclass . - Hence, subclass is specialized version of super class. - We use the keyword extends for inheriting a class from other

Advantages of inheritance: Reusability of code. Effort and time saving. Increased reliability. Implementation of inheritance: Inheriting classes (Extending classes). Creates a new class as an extension of another class. A class cannot be inherited from more than one class. A derived class can only access the non private members of the base class. Inheriting interfaces(Implementing interface) The implements keyword is used to inherit an interface in java. Java allows a class to be inherited from more than one interface.

General form Class <class_name> implements <interfce1>,<interfce2>.. Types of inheritance Single inheritance Multiple inheritance Multilevel inheritance Hierarchical inheritance Hybrid inheritance

Single inheritance: The process of creating only one sub class from only one super class is single inheritance. Super class Subclass class super1 { int a=10; Public void print() { System.out.println("the value of A="+a); } } class sub extends super1 { int b=10; public void sum() { System.out.println("the value of B="+b); int c=a+b; System.out.println("the sum is="+c);; } } class main { public static void main(String args []) { sub a1=new sub(); a1.print(); a1.sum(); } }

interface super1 { int a=10; Public void printa(); } interface super2 { int b=10; Public void printb(); } class sub implements super1,super2 { public void printa(){ System.out.println("the value of A="+a); } public void printb() { System.out.println("the value of B="+b); } public void sum() { int c=a+b; System.out.println("the sum is="+c);; } } class main { public static void main(String args[]) { sub a1=new sub(); a1.printa(); a1.printb(); a1.sum(); } }

Multiple inheritance: The process of creating only one sub class from more than one super class is known as multiple inheritance. Java does not support multiple inheritance. This is implemented with the help of interfaces in java. Super class1 Subclass Super class2

Multilevel inheritance: The process of creating a new sub class from an already existing sub class is known as multilevel inheritance. Super class Subclass Sub - Super class

class super1 { int a=10; public void printa() { System.out.println("the value of A="+a); } } class subsuper extends super1 { int b=10; public void printb() { System.out.println("the value of B="+b); } } class sub extends subsuper { public void sum() { int c=a+b; System.out.println("the sum is="+c);; } } class main { public static void main(String args[]) { sub a1=new sub(); a1.printa(); a1.printb(); a1.sum(); } }

Hierarchical inheritance: The process of creating more than one sub class from an super class is known as Hierarchical inheritance. Super class Subclass2 Sub class1

class super1 { int a=10; public void printa() { System.out.println("the value of A="+a); } } class subclass1 extends super1 { int b=20; public void printb() { System.out.println("the value of B="+b); } } class subclass2 extends super1 { int b=90; public void printb() { System.out.println("the value of B="+b); } } class main { public static void main(String args[]) { subclass1 a1=new subclass1(); a1.printa(); a1.printb(); subclass2 a2=new subclass2(); a2.printa(); a2.printb(); } }

Hybrid inheritance: The process of combining more than one inheritance in classes is known as hybrid inheritance. Super class Sub-super class2 Sub class1 Sub class2

Class hierarchy In java all classes are arranged in a hierarchy. The collection of all classes extending from a common super class is called as an inheritance hierarchy. The classes that appear below a given class in the class hierarchy is termed as descendant class. The classes that appear above a given class in the class hierarchy is termed as ancestor class. Using inheritance a programmer can define a hierarchy of classes. The path from a particular class to its ancestors in the inheritance hierarchy is called as its inheritance chain.

EMPLOYEE EXECUTIVE MANAGER PERSON

ABSTRACT CLASS Abstract classes must be explicitly declared. Classes that cannot be instantiated The abstract modifier is used to create template classes. These are classes that normally are used to provide a superclass for other classes. An abstract class can contain such things as variable declarations and methods but cannot contain code for creating new instances.

An abstract class can also contain abstract methods . These are methods that define return type, name, and arguments but do not include any method body. Subclasses are then required to implement those abstract methods in which they supply a body.

Format: abstract class < class name > { <public/private/protected> abstract method (); }

E.G. Abstract Class abstract class A { abstract void callme (); void callmetoo () { System.out.println ("This is a concrete method."); } } class B extends A { void callme () { System.out.println ("B's implementation of callme ."); } }

class AbstractDemo { public static void main(String args []) { B b = new B(); b.callme (); b.callmetoo (); } }

FINAL KEYWORD The final keyword indicates that an object is fixed and cannot be changed. The three places where final keyword is used are: Data Field Method Class

Final data : Many programming languages have a way to tell the compiler that a piece of data is “constant.” A constant is useful for two reasons: It can be a compile-time constant that won’t ever change. (e.g. value of pi) It can be a value initialized at run-time that you don’t want it to be changed. (e.g. today's temperature) A field that is both static and final has only one piece of storage that cannot be changed.

Final methods There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. The second reason for final methods is it improves the efficiency. Any private methods in a class are implicitly final . Because you can’t access a private method, you can’t override it (the compiler gives an error message if you try). General form: Public final void add() { }

Final classes When you say that an entire class is final (by preceding its definition with the final keyword), you state that you don’t want to inherit any other class from this class. This is done for the reasons of security and efficiency. All methods in the final class are indirectly final. General form: final class <class_name> { member variables; methods(); }

THE OBJECT CLASS The Object class sits at the top of the class hierarchy tree in the Java development environment. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.

Various Methods Supported By The Object Class: The equals Method The getClass Method The toString Method The Clone Method The wait Method The finalize Method The hashCode Method The notify Method The notifyAll Method The toString Method

EQUALS METHOD: The equals method in the object class tests weather one object is equal to another object. public boolean equals( Object  ) Properties of equals method: It is reflexive : for any non-null reference value x, x.equals(x) should return true. It is symmetric : for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive : for any non-null reference values x, y, and z,if x.equals(y) returns true and y.equals(z) returns  true, then x.equals(z)should return true.

It is consistent : for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true. For any non-null reference value x, x.equals(null) should return false. Parameters: obj   - the reference object with which to compare. Returns: true if this object is the same as the obj argument; false otherwise

class A {} class B { public static void main(String args []) { A a =new A(); A b=new A(); if( a.equals (b)) System.out.println ("equal objects"); else System.out.println ("not equal objects"); b=a; if( a.equals (b)) System.out.println ("equal objects"); else System.out.println ("not equal objects"); } }

HASH CODE METHOD: Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. Hash code is got from the objects memory address . public int hashCode() Returns: a hash code value for this object.

The general conditions of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the  equals method , then calling the  hashCode  method on each of the two objects must produce the same integer result.

class A {} class B{ public static void main(String args []){ A a =new A(); A b=new A(); System.out.println ("object a hashcode "+ a.hashCode ()); System.out.println ("object b hashcode "+ b.hashCode ()); b=a; System.out.println ("object a hashcode "+ a.hashCode ()); System.out.println ("object a hashcode "+ b.hashCode ()); } }

TO STRING METHOD: Returns a string representation of the object. In general, the toString method returns a string that " textually represents " this object. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character ` @ ', and the unsigned hexadecimal representation of the hash code of the object. Returns: a string representation of the object.

class A {} class B { public static void main(String args []) { A a =new A(); A b=new A(); System.out.println ("object a String value "+ a.toString ()); System.out.println ("object b String value "+ b.toString ()); } }

THE GETCLASS METHOD public final Class getClass () Returns the runtime class of an object. class A {} class B { public static void main(String args []) { A a =new A(); A b=new A(); System.out.println ("object a belongs to class "+ a.getClass ()); System.out.println ("object b belongs to class "+ b.getClass ()); } }

  clone () Creates a new object of the same class as this object. notify () Wakes up a single thread that is waiting on this object's monitor. notifyAll () Wakes up all threads that are waiting on this object's monitor. wait () Waits to be notified by another thread of a change in this object.

INTERFACES An interface is a way of describing what classes should do, without specifying how they should do it. A class can implement more than one interface. It is a set of requirements for a class. All methods declared in a interface are automatically considered as public.

Properties of interface: Interfaces are not classes (i.e.)one cannot instantiate an interface. Interface variables can be declared. E.g.: <interface name> <variable name>; An interface variable can refer to an object of a class which implements the interface. Fields in interface are public static final. Classes can implement multiple interfaces. Static methods cannot be placed in interfaces. One interface can extend the other interface. E.g.: interface <interface2> extends <interface1>

interface super1 { int a=10; Public void printa(); } interface super2 { int b=10; Public void printb(); } class sub implements super1,super2 { public void printa(){ System.out.println("the value of A="+a); } public void printb() { System.out.println("the value of B="+b); } public void sum() { int c=a+b; System.out.println("the sum is="+c);; } } class main { public static void main(String args[]) { sub a1=new sub(); a1.printa(); a1.printb(); a1.sum(); super1 a11=new sub(); a11.printa(); super2 a111=new sub(); a111.printb(); } }

OBJECT CLONING When a copy of a object is made, the original and the copy objects refer to the same object i.e. the change to one object will affect the other. E.g.: Employee original=new employee(“raj”,50000) Employee copy=original; copy.raiseSalary(10); original copy employee

In order to copy an old object into another new object which should not refer to the old object but the values has to copied to a new reference we use the clone method. Employee original=new employee(“raj”,50000) Employee copy=original.clone(); copy.raiseSalary(10); (or) Employee original=new employee(“raj”,50000) Employee copy=(Employee)original.clone(); copy.raiseSalary(10);

original copy employee employee

Java supports two type of cloning: - Deep cloning shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning. To do cloning a class must Implement the cloneable interface. Redefine the clone method with public access specifier.

Shallow cloning: Shallow clone only copies the top level structure of the object not the lower levels. The clone() method belongs to the Object superclass. Because of this, it can only do a field-by-field copy of the Object. This is fine if all the fields are primitive types or immutable objects, but if the Object contained other mutable sub objects, only the reference will be copied, and the objects will share data.

Original Object Cloned Object Person ----------------------- Name: SSN: SubObject: Person ----------------------- Name: SSN: SubObject: SubObject -----------------------

For every class, you need to decide whether or not The default shallow copy clone is acceptable You need to deep-copy the class The object is not allowed to be cloned For either of the first two choices, you must Implement the Cloneable interface Redefine the clone() method with the public access modifier E.g: public class Employee implements Cloneable { public Employee clone() { return (Employee)super.clone(); }}

DEEP CLONING: If you need to make a deep copy of a class, your clone method must copy any mutable objects within the class. This is more work, but necessary. E.G: public class Employee implements Cloneable { public Employee clone() { Employee cloned=(Employee)super.clone(); cloned.hireday=(Date) hireDay.clone(); return cloned; } }

Original Object Cloned Object Person ----------------------- Name: SSN: Sub Object: Person ----------------------- Name: SSN: SubObject: SubObject ----------------------- SubObject -----------------------

SHALLOW CLONING DEEP CLONING

INNER CLASSES Inner classes are classes defined within other classes The class that includes the inner class is called the outer class There is no particular location where the definition of the inner class (or classes) must be place within the outer class Placing it first or last, however, will guarantee that it is easy to find

An inner class definition is a member of the outer class in the same way that the instance variables and methods of the outer class are members An inner class is local to the outer class definition The name of an inner class may be reused for something else outside the outer class definition If the inner class is private, then the inner class cannot be accessed by name outside the definition of the outer class E.g.: public class Outer { private class Inner { // inner class instance variables // inner class methods } // end of inner class definition // outer class instance variables // outer class methods }

Types of inner classes: Simple inner class Local inner class Anonymous inner class Static inner class Three reasons for using inner class: Inner class methods can access the data from the scope in which they are described.(i.e. private methods of both inner and outer classes) Are hidden from other classes in the same package. Anonymous inner classes are handy when you want to define call back without writing a lot of code.

The .class File for an Inner Class Compiling any class in Java produces a .class file named ClassName .class Compiling a class with one (or more) inner classes causes both (or more) classes to be compiled, and produces two (or more) .class files Such as ClassName .class and ClassName$InnerClassName .class

Nesting Inner Classes It is legal to nest inner classes within inner classes The rules are the same as before, but the names get longer. Given class A , which has public inner class B , which has public inner class C , then the following is valid: A aObject = new A(); A.B bObject = aObject.new B(); A.B.C cObject = bObject.new C();

Local inner class Is an inner class that is declared within the body of a method. These inner classes are not declared with an access specifier. Their scope is restricted to the block in which they are declared. Advantages Completely hidden from outside world All methods of the outer class can create objects of inner class.

Syntax: <access-specifier> class <outer-class name> { code………… <access-specifier> <return-type> <method-name>(arguments) { class <local inner-class name> { code……. } code………. } code……….. }

class outerclass { private int x=1; public void outerdis() { class innerclass { public void innerdisp() { System.out.println("This is local inner class"); System.out.println("The value of X: "+x); } } innerclass inn=new innerclass(); inn.innerdisp(); } } class B { public static void main(String args[]) { outerclass outt=new outerclass(); outt.outerdis(); } }

Anonymous inner class It is a local class without a name. If only one object has to be created from a class, and there is no need to name the class, then an anonymous class definition can be used The class definition is embedded inside the expression with the new operator Anonymous class has no constructors

class outerclass { private int x=1; public void anondis() { anon an=new anon() { public void disp() { System.out.println("This is anonymous inner class"); System.out.println("The value of X: "+x); } }; an.disp(); }} interface anon { public void disp();} class B { public static void main(String args[]) { outerclass outt=new outerclass(); outt.anondis();}}

Static inner class There are certain situations, however, when an inner class must be static. If an object of the inner class is created within a static method of the outer class. If the inner class must have static members.

class outerclass { static int x=1; public static class innerclass { public static void innerdisp() { System.out.println("This is static inner class"); System.out.println("The value of X: "+x); } } } class B{ public static void main(String args[]) { outerclass.innerclass outt=new outerclass.innerclass(); outt.innerdisp(); }}

STRINGS Strings are sequence of characters. Java doesn’t support the string data type. The java library provides the String class to create and manipulate strings. Creating strings: Various constructor supported by String class: String S=new String(); String S=new String(“hello”); String S=new String(char a[]); {char a[]={‘h’,’i’}} String S=new String(char a[],1,1); {char a[]={‘h’,’i’}}

import java.io.*; public class string1 { public static void main(String args []) { char a[]={' b','i','r','t','h','d','a','y '}; String s=new String("hello"); String s1=new String(); String s2=new String(s); String s3=new String(a); String s4=new String(a,5,3); System.out.printf ("s1=%s\ns2=%s\ns3=%s\ns4=%s",s1,s2,s3,s4); } }

Various methods supported by String class: charAt(int index); toLowercase(); toUppercase(); length(); trim(); substring(int beginindex) substring(int begin index,int end index) concat(String str) replace(char oldchar,char newchar) equals(obj name) equalsIgnoreCase() substrings Testing strings for equality String Editing

import java.io.*; public class string1 { public static void main(String args []) { String s=" javaprogram "; String s1=" ing "; System.out.println ("length="+ s.length ()); System.out.println ("without whitespace="+ s.trim ()); System.out.println ("character at="+ s.charAt (7)); System.out.println ("uppercase string="+ s.toUpperCase ()); System.out.println ("lowercase string="+ s.toLowerCase ()); System.out.println (" concat ="+ s.concat (s1)); System.out.println ("substring from index value 3="+ s.substring (3)); System.out.println ("substring of 3 to 7="+ s.substring (3,7)); } }

Concatenation: Means adding two or more strings. Java uses “+” symbol. e.g: import java.io.*; public class string1 { public static void main(String args[]) { String s="java program"; String s1="ing"; String s3=s+s1; System.out.println("after concatenation="+s3); } }

A string can be concatenated with a value also in the similar way. e.g.: import java.io.*; public class string1 { public static void main(String args[]) { String s="java program"; int s1=1; String s3=s+s1; System.out.println("after concatenation="+s3); } }

Java ArrayList The   ArrayList  class is a resizable array, which can be found in the  java.util  package. The difference between a built-in array and an  ArrayList  in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an  ArrayList  whenever you want. The syntax is also slightly different

Thank You…
Tags