120 likes | 179 Views
Inner Classes. In this class, we will cover:. Inner classes What an inner class is Why you would use an inner class Creating an inner class Using an inner class Dangers of inner classes Review for midterm. Inner Classes. An inner class is class defined within another class .
E N D
In this class, we will cover: Inner classes What an inner class is Why you would use an inner class Creating an inner class Using an inner class Dangers of inner classes Review for midterm
Inner Classes • An inner class is class defined within another class. • Why would you want to use inner classes?1. Inner classes can access the implementation of the object that created it - including private data.2. Inner classes can be hidden from other classes in the | same package.3. Anonymous inner classes are handy when you want to define callbacks on the fly.4. Inner classes are very convenient when you are writing event-driven programs.
Creating an Inner Class • See InnerClassTest.java in book. • Special syntax rules for inner classes: • You can use OuterClass.this - not necessary though, it is implied. • e.g. public void actionPerformed(ActionEvent event) { double interest = BankAccount.this.balance * this.rate / 100; BankAccount.this.balance += interest; } • You can also use the object’s name when the inner class occurs outside the scope of the outer class. • e.g. BankAccount mySavings = new BankAccount(10000); BankAccount.InterestAddr adder = mySavings.new InterestAdder(10);
Using an Inner Class to Access Object State • Inner classes are not instance fields of the outer class. • When inner classes construct objects, these objects are local to the methods of the outer class. • With private inner classes, only outer class methods can generate inner class objects. • These inner class objects has access to both its own data fields and the data fields of the outer class fields.
Dangers of Inner Classes • The syntax is complex - unnecessarily so. • Inner classes are genuinely more powerful than regular classes since they have more access privileges - saves some typing. • But you can almost anything you can do with inner classes you can do with regular classes. • It is important to know about inner classes though in case you run across them. • Some would argue that inner classes are more elegant and interesting than they are needed. • Security risks: • The way the compiler handles inner classes exposes private fields and methods to malicious code. • It is relatively easy for someone to manipulate this exposure. • Difficult for programmers to read and maintain.
Summation of Inner Classes • They can be useful for certain situations (like event handling), but use them sparingly. • Be careful when you do use them.
Midterm Review • What have we gone over so far: • Basic syntax of the Java language • Object-oriented terms and concepts • How these concepts translate into code • Inheritance • Interfaces and inner classes