1 / 56

Advanced Java Programming CSE 7345/5345/ NTU 531

Learn about class inheritance, superclass, subclass, final modifier, abstract modifier, polymorphism, interfaces, and inner classes in advanced Java programming.

meden
Download Presentation

Advanced Java Programming CSE 7345/5345/ NTU 531

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Welcome Back!!! Advanced Java ProgrammingCSE 7345/5345/ NTU 531 Session 5

  2. Office Hours: by appt 3:30pm-4:30pm SIC 353 Chantale Laurent-Rice Welcome Back!!! trice75447@aol.com claurent@engr.smu.edu

  3. 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 }

  4. 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(); } }

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  11. 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

  12. Example: final class L { static final int x = 5; } class FinalVariable { public static void main(String[] args) { System.out.println(L.x); } }

  13. 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.

  14. 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.

  15. 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.

  16. 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

  17. 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.

  18. 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 { }

  19. 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(); } }

  20. Answer

  21. 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.

  22. 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.

  23. 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:

  24. 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

  25. 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.

  26. 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.

  27. 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.

  28. 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.

  29. 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; }

  30. 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); } }

  31. Answer

  32. 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.

  33. 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?

  34. 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.

  35. 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.

  36. Variable Hiding • Note: • The declaration of x in class Fhides the declaration of x in class E.

  37. Example: Variable Hiding • class E { int x; } class F extends E { String x; }

  38. 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); } }

  39. Answer f.x = This is a string e.x = 45 Press any key to continue . . .

  40. 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

  41. 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

  42. 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); }

  43. 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; }

  44. Answer con’t public boolean isEven() { return number%2 == 0; } public boolean equals(int anotherNum) { return number == anotherNum; } public String toString() { return number + " "; } }

  45. 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.

  46. 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.

  47. 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

  48. 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.

  49. 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.

  50. 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.

More Related