560 likes | 568 Views
Learn about class inheritance, superclass, subclass, final modifier, abstract modifier, polymorphism, interfaces, and inner classes in advanced Java programming.
E N D
Welcome Back!!! Advanced Java ProgrammingCSE 7345/5345/ NTU 531 Session 5
Office Hours: by appt 3:30pm-4:30pm SIC 353 Chantale Laurent-Rice Welcome Back!!! trice75447@aol.com claurent@engr.smu.edu
In-class Warm-up • Write a method to reverse a string without using the reverse method in the StringBuffer class. The method signature is as follows: public static String reverse(String s) { // Implement it }
Answer public class InClassNotSoWarm { public static void main(String[] args) { System.out.println(reverse("acb")); } public static String reverse(String s) { // Implement it StringBuffer strBuf = new StringBuffer(); for (int i = s.length() - 1; i >= 0; i--) { strBuf.append(s.charAt(i)); } return strBuf.toString(); } }
Chapter 8 Class Inheritance and Interfaces Objectives ·Understand the concept of class inheritance and the relationship between superclasses and subclasses. • ·Create new classes from existing classes. • ·Learn to use the super keyword. • ·Learn to use three modifiers: final, protected, and abstract. • ·Create abstract classes. • ·Understand polymorphism and object casting. • ·Understand the concept of interfaces. • ·Become familiar with inner classes.
Key Concepts • The class derived from the superclass is called the subclass. • Sometimes a superclass is referred to as a parent class or a base class, and a subclass is referred to as a child class, an extended class, or a derived class.
Key Concepts • Subclasses usually have more functionality than their superclasses. • The keywords super and this are used to reference the superclass and the subclass, respectively.
Key Concepts • The final modifier is used to prevent changes to a class, a method, or a variable. • A final class cannot be extended. • A final method cannot be overridden. • A final variable is a constant.
Key Concepts • The abstract modifier is used to design generic superclasses. • An abstract class cannot be instantiated. • An abstract method contains only the method description without implementation. • Its implementation is provided by subclasses.
final • One of the common uses of final is to create named constants. • For example, the following application illustrates this use of final. • It creates a variable x whose value cannot be changed.
Example: Final final class V1 { } class V2 extends V1 { } class FinalClass { public static void main(String args[]) { V1 obj = new V1(); } } //Will not compile because cannot inherit from final V1 //class V2 extends V1 // cannot inherit from final V1 //class V2 extends V1 because final cannot be extended
Example: final class L { static final int x = 5; } class FinalVariable { public static void main(String[] args) { System.out.println(L.x); } }
Inheritance • Using inheritance, you can derive one class, called the derived class or subclass, from another, called the base class or superclass. • The idea here is that you add what you want to the new class to give it more customized functionality than the original class.
Inheritance • Inheritance is the most crucial concepts in object-oriented programming, and it has a very direct effect on how you design and write your Java classes. • Inheritance is a powerful mechanism that means when you write a class you only have to specify how that class is different from some other class; • Inheritance will give you automatic access to the information contained in that other class.
Inheritance • Inheritance is a concept in object-oriented programming in a strict hierarchy. • Each class in the hierarchy has superclasses (classes above it in the hierarchy) and any number of subclasses ( classes below it in the hierarchy). • Subclasses inherit attributes and behavior from their superclasses.
Inheritance Class A Class A is the superclass of B Class B is the subclass of A Class B is the superclass of C, D, E Class C, D and E are subclasses of B Class B Class C Class D Class E
Subclasses • Inheritance allows one class to reuse the functionality provided by its superclasses. • The extends clause in a class declaration establishes an inheritance relationship between two classes. • Syntax: class clsname2 extends clsname1 { //class body } If the extends clause is omitted from the declaration of a class, the Java compiler assumes that Object is its superclass.
class X { } class X1 extends X { } class X2 extends X { } class X11 extends X1 { } Example: Inheritance class X12 extends X2 { } class X21 extends X2 { } class X22 extends X2 { }
Example con’t class InheritanceHierarchy { public static void main(String[] args) { X x; System.out.println(“Instantiating X “); x = new X(); System.out.println(“Instantiating X1 “); x = new X1(); System.out.println(“Instantiating X110 “); x = new X11(); System.out.println(“Instantiating X12 “); x = new X12(); System.out.println(“Instantiating X2 “); x = new X2(); } }
Inheritance • When a class doesn’t do exactly what you want, you can build a new class based on it. • Your class inherits the original class’s methods and instance variables, to which you can add your own code and data.
Inheritance • Inheriting classes is a great way to reuse existing code. • The term code reuse does not refer to a text editor’s cut and paste commands. • Developing reusable code means writing and debugging classes, and then building new classes from them.
interface A { void print();} class C {} class B extends C implements A { public void print() { } } public class Test { public static void main(String[] args) { B b = new B(); if (b instanceof A) System.out.println("b is an instance of A"); if (b instanceof C) System.out.println("b is an instance of C"); } } Nothing. b. b is an instance of A. c. b is an instance of C. d. b is an instance of A followed by b is an instance of C. Show the output of running the class Test in the following code lines:
toString() method • Previous slide answer is D. (b is an instance of A b is an instance of C) • Press any key to continue . . . • The toString() method returns a string equivalent of the current object. • Its signature String toString() It is common for classes to override this method so useful information may be provided via the print() and println() method
Inheritance • Inheritance and variables • The class inherits the state and behavior defined by all of its superclasses. • State is determined by variables; • Behavior is determined by methods. • Therefore, an object has one copy of every instance variable defined not only by its class but also by every superclass of its class.
Inheritance and Variables • A static or instance variable in a subclass may have the same name as a superclass variable. • In that case, the variable hides the superclass variable. • These two variables may have the same type or different types.
Inheritance and variables • The following application demonstrates a class inheritance hierarchy. • Class W extends Object and has one instance variable of type float. • Class X extends W and has one instance variable of type StringBuffer. • Class Y extends X and has one instance variable of type String. • Class Z extends Y and has one instance variable of type Integer.
Inheritance and Variable con’t • An object of class Z has the instance variables that are defined in all of the superclasses. • The main() method instantiates class Z with the new operator, initializes the instance variables, and displays their values.
Example: Inheritance and variables class W { float f; } class X extends W { StringBuffer sb; } class Y extends X { String s; } class Z extends Y { Integer i; }
Example: Inheritance and Variables class Wxyz { public static void main(String[] args) { Z z = new Z(); z.f = 4.567f; z.sb = new StringBuffer(“abcde”); z.s = “ Learning this Inheritance Stuff”; z.i = new Integer(41); System.out.println(“z.f = “ + z.f); System.out.println(“z.sb = “ + z.sb); System.out.println(“z.s = “ + z.s); System.out.println(“z.i = “ + z.i); } }
public class C { public static void main(String[] args) { Object[] o = {new A(), new B()}; System.out.print(o[0]); System.out.print(o[1]); } } class A extends B { public String toString() { return "A"; } } class B { public String toString() { return "B"; } } a. AB b. BA c. AA d. BB e. None of above What is the output of running the class C.
class A { public A() { System.out.println( "The default constructor of A is invoked"); } } class B extends A { public B(String s) { System.out.println(s); } } public class C { public static void main(String[] args) { B b = new B("The constructor of B is invoked"); } } a.none b."The constructor of B is invoked" c. "The default constructor of A is invoked" "The constructor of B is invoked" d. "The default constructor of A is invoked" What is the output of running class C?
Variable Hiding • Previous slide answer is C. • Class E declares an instance variable named x of type int. • Class F is a subclass of E and also declares an instance variable named x of type String • The main() method first creates an objects of class F. A reference to this object is assigned to a local variable named f of type F.
Variable Hiding • f.x is, therefore, of type String. • Next, an object of class E is created. • A reference to this object is assigned to a local variable named e of type E. • The expression e.x is, therefore, of type int.
Variable Hiding • Note: • The declaration of x in class Fhides the declaration of x in class E.
Example: Variable Hiding • class E { int x; } class F extends E { String x; }
Example con’t class Ef { public static void main(String args[]) { F f = new F(); f.x = “This is a string”; System.out.println(“f.x = “ + f.x); E e = new E(); e.x = 45; System.out.println(“e.x = “ + e.x); } }
Answer f.x = This is a string e.x = 45 Press any key to continue . . .
class A1 { void hello() { System.out.println("hello from A1"); } } class B1 extends A1 { void hello() { System.out.println("hello from A1"); } } class C1 extends B1 { void hello() { System.out.println("Hello from C1"); } } public class MethodOverriding { public static void main(String[] args) { C1 obj = new C1(); obj.hello(); } } Method Overriding
Create a class named IntClass as follows: public class IntClass { private int number; public IntClass(int number) { // Implement it } public boolean isPrime() { // Implement it } public static boolean isPrime(int num) { // Implement it } public boolean isEven() { // Implement it } public boolean equals(int anotherNum) { // Implement it } public String toString() { // Implement it } } Another Warm-up
Answer public class NotToKool { public static void main(String[] args) { IntClass n1 = new IntClass(5); System.out.println("n1 is even? " + n1.isEven()); System.out.println("n1 is prime? " + n1.isPrime()); System.out.println("5 is prime? " + IntClass.isPrime(15)); } } class IntClass { private int number; public IntClass(int number) { this.number = number; } public boolean isPrime() { return isPrime(number); }
Answer con’t public static boolean isPrime(int num) { if ((num ==1) || (num ==2)) { return true; } for (int i=2; i<=num/2; i++) { if (num%i == 0) return false; } return true; }
Answer con’t public boolean isEven() { return number%2 == 0; } public boolean equals(int anotherNum) { return number == anotherNum; } public String toString() { return number + " "; } }
Chapt 10 Applets • How applets and Applications Are Different? • Java applications are standalone Java programs that can be run by using just the Java interpreter. • Java applets, however, are from inside a WWW browser.
10 Applets • How Applets and applications are different? • Java applications are standalone Java programs that can be run by using just the Java interpreter • Java applets, however, are from inside a WWW browser, they have access to the structure the browser provides: an existing window, an event-handling and graphics context, and the surrounding user interface.
Example: Java Applet import java.applet.Applet; import java.awt.Graphics; public class FirstApplet extends Applet { public void paint(Graphics g) { g.drawString(“This is my first applet!”, 20, 100); } } Compile this code and then enter the following command appletviewer First Applet.java
Creating Applets • To create an applet, you create a subclass of the class Applet • The Applet class, part of the java.applet package, provides much of the behavior your applet needs to work inside a Java-enabled browser. • Applets also take strong advantage of Java’s Abstract Windowing Toolkit (AWT), which provides behavior for creating graphical user interface (GUI)-based applets and applications:drawing to the screen; creating windows, menu bars, buttons, check boxes, and other UI elements; and managing user input such as mouse clicks and keypresses.
The keyword “super” • It is possible to access a hidden variable by using the super keyword, as follows: super.VarName Here, varName is the name of the variable in the superclass. This syntax may be use to read or write the hidden variable.
Creating applets • To create an applet, you create a subclass of the class Applet. • The applet class, part of the java.applet package provides much of the behavior your applet needs to work inside a java-enabled browser.