AI generated
The Java Class Hierarchy represents the inheritance and relationship between different classes in the Java programming language. At the top of the hierarchy is the Object
class, which is the base class for all other classes in Java.
Java classes are organized in a hierarchical structure, where classes can inherit properties and behaviors from parent classes. This inheritance allows for code reuse and the creation of specialized classes based on existing ones.
The hierarchy includes various classes and interfaces that are part of the Java standard library, such as String
, Integer
, ArrayList
, and Exception
. These classes are grouped based on their common characteristics and functionality.
Developers can create their own classes that extend existing classes or implement interfaces, further expanding the Java Class Hierarchy. This enables the creation of custom classes tailored to specific needs while leveraging the functionality provided by parent classes and interfaces.
Understanding the Java Class Hierarchy is crucial for effective object-oriented programming in Java, as it allows developers to utilize existing classes, create class relationships, and design well-structured and maintainable code.
Can a subclass extend multiple parent classes?
Problem:
f()
is not overridden, which f()
do we use in C3 ?Java DOES NOT ALLOW Multiple Inheritance.
C++ allows this if C1 and C2 have no conflicts.
public boolean equals(Object o)
→ Defaults to pointer equality
x==y
→ invokes x.equals(y)
public String toString()
→ converts values if the instance variables to String
o
, use System.put.print(o+"");
o.toString()
We can exploit the tree like structure to write generic functions:
Example: Search for an element in an array:
public int find(Object[] objarr, Object o){
int i;
for( i=0; i < objarr.length ; i++ ){
if(objarr[i] == o) { return i }; // == is pointer equality by default
}
return (-1);
}
If a class overrides equals()
, dynamic dispatch will use the redefined function instead of Object.equals()
for objarr[i]==o
Example: A class Date with the instance variables day
month
year
.
Wish to override equals()
to compare the object state as follows:
public boolean equals(Date d){
return ( (this.day==d.day) &&
(this.month==this.month) &&
(this.year == this.year));
}
Unfortunately → boolean equals(Date d)
does not override boolean equals(Object o)
So , instead should write :
public boolean equals(Object d){
if( d instanceof Date){ //Run time type check
Date myd = (Date) d; // Type cast
return ((this.day == myd.day) &&
(this.month == myd.month) &&
(this.year == myd.year));
}
return false;
}