510 likes | 587 Views
Welcome Back!!!. Advanced Java Programming CSE 7345/5345/ NTU 531. Session 6. Office Hours: by appt 3:30pm-4:30pm SIC 353. Chantale Laurent-Rice. Welcome Back!!!. trice75447@aol.com. claurent@engr.smu.edu. Inheritance. Class A. Class A is the superclass of B
E N D
Welcome Back!!! Advanced Java ProgrammingCSE 7345/5345/ NTU 531 Session 6
Office Hours: by appt 3:30pm-4:30pm SIC 353 Chantale Laurent-Rice Welcome Back!!! trice75447@aol.com claurent@engr.smu.edu
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
Why Inheritance? • Using inheritance allows you to base your classes on other classes, reusing code and adding to it • Allows you to use or redefine the members of the superclass as you like, customizing that class for your own use
Why Inheritance? con’t.. • In fact, you can create classes that must be treated as superclasses. • These classes are called abstract classes • An abstract class cannot be instantiated directly into an object; you must instead derive a new class from it first, overriding those members that are specifically declared abstract.
Why inheritance? • Java is truly an OOP, and it relies on inheritance a great deal. • The developers at Sun Microsystems have created huge packages – class libraries – full of classes that you can use as superclasses. • This is important if, for example you want to create an applet in Java.
Applet from the java.Applet package’s class import java.applet.Applet; import java.awt.*; public class applet extends Applet { public void paint(Graphics g) { g.drawString("this creates a superclass based on the Applet class " + "using the extends keyword ", 20, 50); } }
import java.awt.*; import java.awt.event.*; class AppletFrame extends Frame { public void paint(Graphics g) { g.drawString("this creates a windowed application and" + "basing the window, itself on the java.awt.Frame class ", 20, 50); } } public class Application1 { public static void main(String[] args) { AppletFrame dframe = new AppletFrame(); dframe.setSize(800, 200); dframe.addWindowListener(new WindowAdapter(){ public void WindowClosing(WindowEvent e) { System.exit(0);} }); dframe.show(); } } Applet from the java.awt.frame
Why interfaces? • An interface is a list of method that define some kind of behavior • And are provided without implementation • A class may implement many interfaces
Why interfaces? con’t • Suppose you want to create an Applet that handles button clicks. • To create a standard applet, you can derive a class from the java.applet.Applet class, and to handle button clicks, you use another class, named ActionListener.
Why interfaces? con’t • Therefore, it looks as though you’ll have to base your applet on both the Applet and the ActionListener classes. • However, basing a subclass on two or more superclasses is called multiple inheritance, and it turns out that Java doesn’t support multiple inheritance (C++ do). • In practice, this means you can only use the extends keyword with one class.
Why interfaces? con’t • To solve this problem, Java implements classes such as ActionListener as interfaces. • That means you can extend your applet from the Applet class and use the implements keyword to add the button-click handling.
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class ClickerInterface extends Applet implements ActionListener { TextField textbox; Button button; public void init() { textbox = new TextField(20); add(textbox); button = new Button("Click Here!"); add(button); button.addActionListener(this); } public void actionPerformed(ActionEvent e) { String message = new String("It's showtime!"); if(e.getSource() == button) { textbox.setText(message); } } } Example:Interface
class Vehicle { public void start() { System.out.println("Starting..."); } } class Car extends Vehicle { public void drive() { System.out.println("driving..."); } } class Aircraft extends Vehicle { public void fly() { System.out.println("I am flying..."); } } class Helicopter extends Aircraft { public void heli() { System.out.println("heling..."); } } class Jet extends Aircraft { public void jetty() { System.out.println("escaping..."); } } Multiple Inheritance
Multiple Inheritance public class DVehicle { public static void main(String[] args) { System.out.println("Creating an multilevel Inheritance... "); Car DCar = new Car(); DCar.start(); DCar.drive(); DCar.fly(); System.out.println(); System.out.println("Creating another inheritance level "); Jet DJet = new Jet(); DJet.start(); DJet.fly(); DJet.jetty(); } }
Class Modifiers • There are three possible modifiers that may precede the class keyword. • Keywordmeaning abstract Cannot be instantiated final Cannot be extended public Can be accessed by any other class. If this word is missing, access to the class is limited to the current package.
abstract • Abstract classes are very important in object-oriented programming. • In some cases, writing classes can provide general code. It’s up to the developer who subclasses your class to customize it. • To make sure the developer customizes your code, you can make the method abstract, which means the developer will have to override your method; otherwise Java will complain.
class DAbstract { String getData(); public void print(); { System.out.println(getData()); } } Note there’s no implementation of the getData() method because I want the developers to specify what data they want to print out. To make sure that they know that they must provide an implementation of the getData method, I must make the method abstract. abstract
abstract MakingItAbstract { String getData(); public void print(); { System.out.println(getData()); } } Now when you use subclass MakingItAbstract, You have to provide an implementation of getData abstract
abstract class MakingItAbstract { abstract String getData(); public void print() { System.out.println(getData()); } } class Ex extends MakingItAbstract { String getData() { return "Hello I am implementing the getData()"; } } public class PuttingSubclasstoWork { public static void main(String[] args) { System.out.println("Putting the subclass to work"); Ex DEx = new Ex(); DEx.print(); } } Abstract con’t
Inheritance con’tMethod Overriding • Method Overriding occurs when a class declares a method that has the same type signature as a method declared by one of its superclasses. • When a method in a subclass overrides a method in a superclass, the method in the superclass is hidden relative to the subclass object.
Method Overriding • Method overriding is a very important capability because it forms the basis for run-time polymorphism. • Polymorphism means “One interface, multiple implementations.” • The signature of the method defines the interface, and each overridden version provides a unique implementation.
Example: method overridden class animal { public void breathe() { System.out.println("Is Breathing"); } } class fish extends animal { public void breathe() //overriding the breathe method in the fish class { System.out.println("Is bubbling"); } }
Example con’t public class Overriding { public static void main(String[] args) { System.out.println("Creating an animal... "); animal DAnimal = new animal(); DAnimal.breathe(); System.out.println(); System.out.println("Creating fish"); fish DFish = new fish(); DFish.breathe(); } }
The keyword “super” • It is possible to access overriding members by using the super keyword • Super much like this keyword except that super doesn’t refer in the current object but rather to its superclass.
Example: Keyword “super” class animal2 { public void breathe() { System.out.println("Is Breathing"); } } class fish extends animal2 { public void breathe() //overriding the breathe method in the fish class { System.out.println("Is bubbling"); } public void newBreathe() { super.breathe(); } }
Example con’t public class AccessingWithSuper { public static void main(String[] args) { System.out.println("Creating an animal... "); animal DAnimal = new animal(); DAnimal.breathe(); System.out.println(); System.out.println("Creating fish"); fish SuperFish = new fish(); SuperFish.newBreathe();// breathing } }
Final class • The final class cannot be extended. • Classes are sometimes declared in this manner so the methods implemented by that class cannot be overridden. • For example, the Math class is final. • If a class is final, all of its methods are also final.
Example: final class animal3 { public void breathe() { System.out.println("Is Breathing"); } } class fish extends animal3 { public void breathe() //overriding the breathe method in the fish class { System.out.println("Is bubbling"); } }
From Animal3() C:\animal3.java:8: cannot inherit from final animal3 class fish extends animal3 ^ 1 error Tool completed with exit code 1 From Main() .\animal3.java:8: cannot inherit from final animal3 class fish extends animal3 ^ C:\OverridingFinal.java:13: cannot resolve symbol symbol : method newBreathe () location: class fish OverFish.newBreathe();//breathing ^ 2 errors Tool completed with exit code 1 Answer….error
Inheritance and methods • The previous section described how method overriding operates in an inheritance hierarchy. • The dynamic dispatch mechanism in Java automatically selects the correct version for execution based upon the type of objects being referred to at the time the method is executed.
Inheritance and methods • Thus, an overriding method masks the one defined by the superclass. But this raises an interesting question: • What if you want to access the functionality present in the superclass version of an overridden method? • To access a superclass method use the super keyword
Inheritance and constructors • The state and behavior of a class are defined not only by that class but also by each of its superclasses. • Therefore, in order to correctly initialize an object, it is not sufficient to execute a constructor only for one class. • A constructor for each superclass must also be executed.
Inheritance and constructors • Furthermore, a superclass constructor must execute before a subclass constructor. • This is necessary so the state and behavior defined by the superclass may be correctly and completely initialized before the subclass constructor executes.
“super” vs. “this” • The super keyword is used to explicitly invoke a superclass constructor. • The this keyword is used for a constructor to invoke another constructor in the same class. • If you use this form, it must appear as the first statement of the constructor. • Therefore, a given constructor cannot use both super() and this().
“super” vs. “this” • However, if you write a constructor that does not use either super() or this() to explicitly invoke another constructor, the Java compiler automatically calls super() to invoke the default superclass constructor. • Recall that a default constructor has no arguments.
“super” vs., “this” • In other words, the Java compiler assumes that the first line of every constructor is an implicit call to the default superclass constructor unless you explicitly use super() or this() to request different behavior.
Example: class S1 { int s1; S1() { System.out.println(“S1 Constructor”); s1 =1; } } class T1 extends S1 { int t1; T1() { System.out.println(“T1 Constructor”); t1 = 2; } }
class U1 extends T1 { int u1; U1() { System.out.println("U1 Constructor"); u1 = 3; } } class InheritanceAndConstructors1 { public static void main(String[] args) { U1 u1 = new U1(); System.out.println("u1.s1 = " + u1.s1); System.out.println("u1.t1 = " + u1.t1); System.out.println("u1.u1 = " + u1.u1); } } class S1 { int s1; S1() { System.out.println("S1 Constructor"); s1 =1; } } class T1 extends S1 { int t1; T1() { System.out.println("T1 Constructor"); t1 = 2; } } Example con’t
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.
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.
Creating applets con’t • Applets also take strong advantage of Java’s Abstract Windowing Toolkit 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 AWT classes are part of the java.awt.package.
Major applet activities • To create a basic Java application, your class has to have one method, main() method, with a specific signature. • Then, when your application runs, main() is found and executed, and from main() you can set up the behavior that your program needs to run.
Creating applets con’t • Applets are similar but more complicated - and in facts, applets don’t need a main() method at all. • Applets have many different activities that correspond to various major events in the life cycle of the applet. For example, initialization, painting, and mouse events. Each activities has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods.
5 important Applets methods Initialization- occurs when the applet is first loaded or reloaded, similar to the main() method. public void init(){... } Starting- start the applet (can happen many different times during an applet’s lifetime. public void start(){... }
5 important Applets methods con’t • Painting- is the way the applet actually draws something on the screen, be it text, a line, a colored background, or an image. • public void paint(Graphics g){…..}
5 important applets methods con’t Stopping- goes hand in hand with starting. Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop(). public void stop(){….} • Destroying- enables the applet to clean up after itself just before it is freed or the browser exits. • public void destroy(){…. }
The life cycle of an applet • They are defined by the java.applet.Applet class and, therefore, are inherited by every applet. • init()- is called only when the applet begins execution. • start()- is executed after the init() method completes execution. • stop()- is invoke when the applet viewer is minimized and start() is called when the applet viewer is later maximized. • destroy()- is called by the applet viewer or Web browser before the applet is terminated.
Applet and its superclasses Java.lang.Object Java.awt.Component Java.awt.Container Java.awt.Panel Java.applet.Applet
import java.awt.event.*; import java.applet.*; import java.awt.*; /* <APPLET CODE=Password2.class WIDTH=300 HEIGHT=300> </APPLET>*/ public class Password2 extends Applet implements ActionListener { public TextField text1; public TextField text2; Example: Applet