Exercise. Zheng-Liang Lu Java Programming 273 / 324
|
|
- Shannon Mills
- 5 years ago
- Views:
Transcription
1 Exercise Zheng-Liang Lu Java Programming 273 / 324
2 1 public class AnimalFamilyDemo { 2 public static void main(string[] args) { 3 Dog d = new Dog(); 4 d.sleep(); 5 d.eat(); 6 d.watchdoor(); 7 8 Animal a = d; // upcasting 9 a.sleep(); 10 a.eat(); 11 a.watchdoor(); // oops, invisible! 12 a.chaselittlething(); // oops, invisible! d = (Dog) a; // downcasting 15 d.watchdoor(); // works! 16 } 17 } Zheng-Liang Lu Java Programming 274 / 324
3 Field Hiding with Polymorphism You can refer to hidden fields simply by casting an object to a variable of the appropriate superclass. 1 class T { 2 int x = 1; 3 } 4 5 class U extends T { 6 int x = 2; 7 } 8 9 public class FieldHidingDemo { 10 public static void main(string[] args) { 11 U u = new U(); 12 System.out.println(u.x); // output 2 13 T t = u; 14 System.out.println(t.x); // output 1 15 } 16 } Zheng-Liang Lu Java Programming 275 / 324
4 Method Overriding with Polymorphism However, you cannot invoke overridden methods by upcasting. JVM calls the appropriate method for the object. Method lookup starts from the bottom of the class hierarchy to the top. Always looking for the most specific method body. These methods are referred to as virtual methods. This mechanism preserves the behaviors of the objects and the superclass type variables play the role of placeholders. Zheng-Liang Lu Java Programming 276 / 324
5 Example Imagine that we have a zoo with some animals. 1 class Animal { 2 void speak() {} 3 } 4 5 class Dog extends Animal { 6 void speak() { 7 System.out.println("woof"); 8 } 9 } class Cat extends Animal { 12 void speak() { 13 System.out.println("meow"); 14 } 15 } class Bird extends Animal { 18 void speak() { 19 System.out.println("tweet"); Zheng-Liang Lu Java Programming 277 / 324
6 20 } 21 } public class PolymorphismDemo { 24 public static void main(string[] args) { 25 Animal[] zoo = {new Dog(), new Cat(), new Bird()}; 26 for (Animal a: zoo) { 27 a.speak(); 28 } 29 } 30 } Zheng-Liang Lu Java Programming 278 / 324
7 The final Keyword A final variable is a variable which can be initialized once and cannot be changed later. The compiler makes sure that you can do it only once. A final variable is often declared with static keyword and treated as a constant, for example, Math.PI. A final method is a method which cannot be overridden by subclasses. You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. A class that is declared final cannot be inherited. Zheng-Liang Lu Java Programming 279 / 324
8 1 class A { 2 final int x = 1; 3 Example 4 final void foo() { 5 x = x + 1; // oops, you cannot change a final variable 6 System.out.println("old foo"); 7 } 8 } 9 10 final class B extends A { 11 int y = 2; // cannot be overrided 14 void foo() { 15 System.out.println("my new foo"); 16 } 17 } class C extends B {} // oops, B cannnot be inherited Zheng-Liang Lu Java Programming 280 / 324
9 23 public class FinalKeywordDemo { 24 public static void main(string[] args) { final B b = new B(); 27 System.out.println(b.x); // output 1 28 b.foo(); b.y = 3; // ok 31 b = new B(); // oops, cannot reference to a new object 32 } 33 } Zheng-Liang Lu Java Programming 281 / 324
10 Abstract Class An abstract class is a class declared abstract. The classes that sit at the top of an object hierarchy are typically abstract classes. 1 These abstract class may or may not have abstract methods, which are methods declared without implementation. More explicitly, the methods are declared without braces, and followed by a semicolon. If a class has one or more abstract methods, then the class itself must be declared abstract. All abstract classes cannot be instantiated. Moreover, abstract classes act as placeholders for the subclass objects. 1 The classes that sit near the bottom of the hierarchy are called concrete classes. Zheng-Liang Lu Java Programming 282 / 324
11 Example Abstract methods and classes are in italic. In this example, the abstract method draw() and resize() should be implemented depending on the real shape. Zheng-Liang Lu Java Programming 283 / 324
12 Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from Animal and Airplane inherited from Transportation. Both Bird and Airplane are able to be in the sky. So they should perform the method canfly(), for example. By semantics, the method canfly() could not be defined in their superclasses. We need a horizontal relationship. Zheng-Liang Lu Java Programming 284 / 324
13 Example 1 interface Flyable { 2 void canfly(); // public + abstract 3 } 4 5 abstract class Animal {} 6 7 class Bird extends Animal implements Flyable { 8 public void canfly() { 9 System.out.println("Bird flying..."); 10 } 11 } abstract class Transportation {} class Airplane extends Transportation implements Flyable { 16 public void canfly() { 17 System.out.println("Airplane flying..."); 18 } 19 } Zheng-Liang Lu Java Programming 285 / 324
14 1 public class interfacedemo { 2 public static void main(string[] args) { 3 Airplane a = new Airplane(); 4 a.canfly(); 5 6 Bird b = new Bird(); 7 b.canfly(); 8 9 Flyable f = a; 10 f.canfly(); // output Airplane flying f = b; 12 f.canfly(); // output Bird flying } 14 } Zheng-Liang Lu Java Programming 286 / 324
15 Interfaces An interface forms a contract between the object and the outside world. For example, the buttons on the television set are the interface between you and the electrical wiring on the other side of its plastic casing. An interface is also a reference type, just like classes, in which only method signatures are defined. So they can be the types of reference variables! Note that interfaces cannot be instantiated (directly). A class implementing one or multiple interfaces provides method bodies for each defined method signature. This allows a class to play different roles, with each role providing a different set of services. Zheng-Liang Lu Java Programming 287 / 324
16 Example Zheng-Liang Lu Java Programming 288 / 324
17 1 interface Driveable { 2 void startengine(); 3 void stopengine(); 4 void accelerate(); 5 void turn(); 6 } 1 class Automobile implements Driveable { 2 public void startengine() {... } 3... // and so on 4 public void honkhorn() {... } } 7 8 class Lawnmower implements Driveable { 9 public void startengine() {... } // and so on 11 public void cutgrass() {... } } Zheng-Liang Lu Java Programming 289 / 324
18 Properties of Interfaces The methods of an interface are implicitly public. In most cases, the class which implements the interface should implement all the methods defined in the interface. Otherwise, the class should be abstract. An interface can declare only fields which are static and final. You can also define static methods in the interface. A new feature since Java SE 8 allows to define the methods with implementation in the interface. A method with implementation in the interface is declared default. Zheng-Liang Lu Java Programming 290 / 324
19 An interface can extend another interface, just like a class which can extend another class. However, an interface can extend many interfaces as you need. For example, Driveable and Updateable are good interface names. Common interfaces are Runnable 2, Serializable 3, and Collection 4. 2 Related to multithreading. 3 Aka object serialization where an object can be represented as a sequence of bytes that includes the object s data as well as information about the object s type and the types of data stored in the object. 4 Collections are data structures that are fundamental to all types of programming. Zheng-Liang Lu Java Programming 291 / 324
20 Timing for Interfaces and Abstract Classes Consider using abstract classes if any of these statements apply to your situation: share code among several closely related classes declare non-static or non-final fields Consider using interfaces if any of these statements apply to your situation: unrelated classes would implement your interface specify the behavior of a particular data type, but not concerned about who implements its behavior take advantage of multiple inheritance Zheng-Liang Lu Java Programming 292 / 324
21 Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation of the value double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 293 / 324
22 Zheng-Liang Lu Java Programming 294 / 324
23 Autoboxing and Unboxing of Primitives The Java compiler automatically wraps the primitives in their wrapper types, and unwraps them where appropriate Integer i = 1; // autoboxing 3 Integer j = 1; 4 System.out.println(i + j); // unboxing; output System.out.println(i == j); // output true 7 System.out.println(i.equals(j)); // output true 8... The method equals() inherited from Object is used to compare the contents of two objects. Herein, the values of wrapper objects. Zheng-Liang Lu Java Programming 295 / 324
24 Immutable Objects An object is considered immutable if its state cannot change after it is constructed. Often used for value objects. Imagine that there is a pool for immutable objects. After the value object is first created, this value object is reused if needed. This implies that another object is created when we operate on the immutable object. Zheng-Liang Lu Java Programming 296 / 324
25 For example, k = new Integer(1); 3 System.out.println(i == k); // output false (why?) 4 System.out.println(k.equals(i)); // output true 5 6 Integer q = 2; 7 i++; 8 System.out.println(i == q); // output true 9 System.out.println(i.equals(q)); // output true Good practice when it comes to concurrent programming. 5 Another example is String objects. 5 See Zheng-Liang Lu Java Programming 297 / 324
26 enum Types 6 An enum type is an reference type limited to an explicit set of values. An order among these values is defined by their order of declaration. There exists a correspondence with string names identical to the name declared. 6 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 298 / 324
27 Example enum Weekday {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} 3... Actually, Weekday is a subclass of enum type with seven static and final objects corresponding to the seven enumerated values. The Weekday instances which really exist are the seven enumerated values. So this mechanism enhances type safety! Zheng-Liang Lu Java Programming 299 / 324
28 1 public class EnumerationDemo { 2 public static void main(string[] args) { 3 Weekday[] weekdays = Weekday.values(); 4 // The method values() returns a Weekday array. 5 6 for (Weekday day: weekdays) { 7 System.out.println(day); 8 } 9 10 Weekday today = Weekday.Sunday; 11 Weekday tomorrow = Weekday.Monday; System.out.println(today == tomorrow); // output false 14 } 15 } Zheng-Liang Lu Java Programming 300 / 324
29 Exercise: Colors 1 enum Color { 2 3 Red, Green, Blue; // three options 4 5 static Color randomcolor() { 6 Color[] colorset = values(); 7 int pickonecolor = (int) (Math.random() colorset. length); 8 return colorset[pickonecolor]; 9 } 10 } public class EnumDemo { 13 public static void main(string[] args) { 14 for(int i = 1 ; i <= 3; i++) 15 System.out.println(Color.randomColor()); 16 } 17 } Zheng-Liang Lu Java Programming 301 / 324
30 Exercise: Size 1 enum Size { 2 3 Large("L"), Medium("M"), Small("S"); // three options 4 5 private String abbr; 6 private Size(String abbr) { this.abbr = abbr; } 7 8 public String getabbreviation() { 9 return this.abbr; 10 } 11 } public class EnumDemo { 14 public static void main(string[] args) { 15 System.out.println(Size.Small.getAbbreviation()); // output S 16 } 17 } Zheng-Liang Lu Java Programming 302 / 324
31 Packages We bundle groups of related types into packages for the following 3 purposes: To make types easier to find and use To avoid naming conflicts To control access Note that types refers to classes, interfaces, and enumerations. For example, fundamental classes are in java.lang and classes for I/O are in java.io. Zheng-Liang Lu Java Programming 303 / 324
32 Access Control Scope \ Modifier private (default) protected public Within the class Within the package x Inherited classes x x Out of package x x x Zheng-Liang Lu Java Programming 304 / 324
33 Nested Classes A nested class is a member of its enclosing class. Non-static nested classes, aka inner classes, have access to other members of the enclosing class, even if they are declared private. Instead, static nested classes do not have access to other instance members of the enclosing class. Timing of usage: Logically grouping classes that are only used in one place Increasing encapsulation Leading to more readable and maintainable code Zheng-Liang Lu Java Programming 305 / 324
34 Family of Nested Classes Zheng-Liang Lu Java Programming 306 / 324
35 Inner Classes Inner classes are of three types depending on how and where you define them. Inner class Method-local inner class Anonymous inner class All cannot define or declare any static members. Unlike a normal class, an inner class can be declared private. Once an inner class is declared private, it cannot be accessed from an object outside the class. Note that the creation of inner type objects is available after the outer type object is created. In other words, you cannot invoke the constructor of the inner type without having the outer type object. Zheng-Liang Lu Java Programming 307 / 324
36 Example: Inner Class 1 class OuterClass { 2 private int x = 1; 3 InnerClass innerclassinstance = new InnerClass(); 4 5 class InnerClass { 6 public void print() { 7 System.out.println(x); 8 } 9 } 10 } public class InnerClassDemo { 13 public static void main(string[] args) { 14 OuterClass outer = new OuterClass(); 15 outer.innerclassinstance.print(); InnerClass inner = new InnerClass(); // oops 18 // Since InnerClass type cannot be resolved out of OuterClass. 19 } 20 } Zheng-Liang Lu Java Programming 308 / 324
37 Example: Method-local Inner Class 1 class OuterClass { 2 private int x = 1; 3 4 void outerclassmethod() { 5 class MLInnerClass { 6 int y = 2; 7 static int z = 3; // implicitly final 8 9 void print() { 10 System.out.println(x); 11 System.out.println(y); 12 System.out.println(z); 13 } 14 } MLInnerClass MLInnerClassInstance = new MLInnerClass(); 17 MLInnerClassInstance.print(); 18 } 19 } Zheng-Liang Lu Java Programming 309 / 324
38 Anonymous Inner Class Anonymous inner classes are an extension of the syntax of the new operation, enabling you to declare and instantiate a class at the same time. However, these do not have a name. Use them when you need to use these types only once. An anonymous class cannot define any static fields, methods, and classes, except for static final constants. Zheng-Liang Lu Java Programming 310 / 324
39 Example 1 abstract class A { 2 void foo(); 3 } 4 5 public class AnonymousClassDemoOne { 6 public static void main(string[] args) { 7 A a = new A() { 8 void foo() {} 9 void hoo() {} 10 }; a.foo(); 13 a.hoo(); // oops 14 } 15 } Since there is no definition of hoo() in A, a.hoo() is not allowed. Zheng-Liang Lu Java Programming 311 / 324
40 Exercise 1 interface B { 2 void foo(); 3 } 4 5 public class AnonymousClassDemoTwo { 6 public static void main(string[] args) { 7 B b = new B() { 8 public void foo() {} 9 void hoo() {} 10 }; y.foo(); 13 y.hoo(); // oops 14 } 15 } An interface can be used to instantiate an object indirectly by anonymous classes with implementing the abstract methods. Zheng-Liang Lu Java Programming 312 / 324
41 Adapters An important use of inner classes is to define an adapter class as a helper. Using adapter classes, we can write classes more naturally, without having to anticipate every conceivable user s needs in advance. Instead, you provide adapter classes that marry your class to a particular interface. For example, an iterator is a simple and standard interface to enumerate objects. The java.util.iterator interface defines two methods: public boolean hasnext() and public Object next(). Zheng-Liang Lu Java Programming 313 / 324
42 Example: An Iterator 1 abstract class Employee {} 2 class CEO extends Employee { 3 public String tostring() { 4 return "CEO"; 5 } 6 } 7 class Manager extends Employee { 8 public String tostring() { 9 return "Manager"; 10 } 11 } 1 public class IteratorDemo { 2 public static void main(string[] args) { 3 EmployeeRepository x; 4 x = new EmployeeRepository(new CEO(), new Manager()); 5 x.list(); 6 } 7 } Zheng-Liang Lu Java Programming 314 / 324
43 1 import java.util.iterator; 2 3 class EmployeeRepository { 4 private Employee[] employees; 5 6 EmployeeRepository(Employee...inputList) { 7 employees = inputlist; 8 } 9 10 private Iterator iter = new Iterator() { 11 int num = 0; public boolean hasnext() { 14 return num < employees.length; 15 } public Object next() { 18 if (hasnext()) { 19 return employees[num++]; 20 } else { 21 return null; 22 } 23 } 24 }; Zheng-Liang Lu Java Programming 315 / 324
44 25 26 void list() { 27 while (this.iter.hasnext()) { 28 System.out.println(this.iter.next()); 29 } 30 } 31 } Zheng-Liang Lu Java Programming 316 / 324
45 Lambda Expressions Lambda expressions allow small bits of code to be written inline as literals and facilitate a more functional style of programming Java. Since Java SE 8, lambda expressions are used to replace anonymous inner classes. You can find a detailed tutorial for lambda expressions from tutorials/obe/java/lambda-quickstart/. Check the example using the Function interface. Read javaoo/lambdaexpressions.html. If you are interested in the origin of Lambda expressions, read Zheng-Liang Lu Java Programming 317 / 324
46 Example 1 public class LambdaExpressionDemo { 2 3 public static void main(string[] args) { 4 Runnable r1 = new Runnable() { 5 public void run() { 6 System.out.println("R1..."); 7 } 8 }; 9 10 Runnable r2 = () > System.out.println("R2..."); r1.run(); 13 r2.run(); 14 } 15 } Zheng-Liang Lu Java Programming 318 / 324
47 Static Nested Class A static inner class is a nested class which is a static member of the outer class. So they can access to other static members without instantiating the outer class. Just like static members, a static nested class does not have access to the instance members of the outer class. Most important, a static nested class can be instantiated directly, without instantiating the outer class object first. Static nested classes act something like a minipackage. Zheng-Liang Lu Java Programming 319 / 324
48 Example 1 class OuterClass { 2 static int x = 1; 3 int y = 2; 4 5 void OuterClassMethod() { 6 System.out.println(y); 7 } 8 9 static class StaticNestedClass { 10 int z = 3; 11 void StaticNestedClassMethod() { 12 System.out.println(x); 13 System.out.println(y); // Oops, static members cannot access to instance members. 14 System.out.println(z); 15 } 16 } 17 } Zheng-Liang Lu Java Programming 320 / 324
49 1 public class StaticNestedClassDemo { 2 public static void main(string[] args) { 3 OuterClass.StaticNestedClass x = new OuterClass. StaticNestedClass(); 4 x.staticnestedclassmethod(); 5 } 6 } Zheng-Liang Lu Java Programming 321 / 324
50 Classpath 7 The variable classpath is a environment variable for the Java compiler to specify the location of user-defined classes and packages. By default, only the packages of the JDK standard API and extension packages are accessible without needing to set where to find them. The path for all user-defined packages and libraries must be set in the command-line (or in the Manifest associated with the JAR file containing the classes). 7 Zheng-Liang Lu Java Programming 322 / 324
51 Usage of Classpath You may use the following command in any terminal: java -cp [the absolute path of the classes or packages] [the full name of the application to run] For Windows users, try java -cp c:\workspace\project train.java.helloworld On Linux/Unix/Mac OS users, try java -cp /workspace/project train.java.helloworld Zheng-Liang Lu Java Programming 323 / 324
52 Java Archive (JAR) 9 JAR is a packed format typically used to aggregate many Java class files, associated metadata 8 and resources (text, images, etc.) into one file to distribute the application software or libraries running on the Java platform. Try an executable JAR! 8 Metadata refers data of data. 9 See Zheng-Liang Lu Java Programming 324 / 324
Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321
Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation
More informationTiming for Interfaces and Abstract Classes
Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces
More informationAnother IS-A Relationship
Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from
More informationA final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.
final A final variable is a variable which can be initialized once and cannot be changed later. The compiler makes sure that you can do it only once. A final variable is often declared with static keyword
More informationSubtype Polymorphism
Subtype Polymorphism For convenience, let U be a subtype of T. Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties
More informationMethod Overriding. Note that you can invoke the overridden method through the use of the keyword super.
Method Overriding The subclass is allowed to change the behavior inherited from its superclass, if needed. If one defines an instance method with its method name, parameters, and its return type, all identical
More informationHAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all
More informationInterfaces. An interface forms a contract between the object and the outside world.
Interfaces An interface forms a contract between the object and the outside world. For example, the buttons on the television set are the interface between you and the electrical wiring on the other side
More informationMethod Overriding. Note that you can invoke the overridden method through the use of the keyword super.
Method Overriding The subclass is allowed to change the behavior inherited from its superclass, if needed. If one defines an instance method with its method name, parameters, and also return type, all
More informationInterfaces (1/2) An interface forms a contract between the object and the outside world.
Interfaces (1/2) An interface forms a contract between the object and the outside world. For example, the buttons on remote controls for some machine. As you can see, an interface is a reference type,
More informationenum Types 1 1 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 267 / 287
enum Types 1 An enum type is an reference type limited to an explicit set of values. An order among these values is defined by their order of declaration. There exists a correspondence with string names
More informationMore Relationships Between Classes
More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to
More informationFirst IS-A Relationship: Inheritance
First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class
More informationMore About Objects. Zheng-Liang Lu Java Programming 255 / 282
More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism
More informationJava Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University
Java Programming 2 Zheng-Liang Lu Department of Computer Science & Information Engineering National Taiwan University Java2 304 Fall 2018 1 class Lecture7 { 2 3 // Object Oriented Programming 4 5 } 6 7
More informationExercise: Singleton 1
Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance
More informationJava Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University
Java Programming 2 Zheng-Liang Lu Department of Computer Science & Information Engineering National Taiwan University Java2 306 Fall 2018 1 class Lecture7 { 2 3 // Object Oriented Programming 4 5 } 6 7
More informationHAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all
More informationHAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.
HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,
More informationExample: Count of Points
Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x
More informationContents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
More informationExample: Count of Points
Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;
More informationLecture 2: Java & Javadoc
Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationPROGRAMMING III OOP. JAVA LANGUAGE COURSE
COURSE 3 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Classes Objects Object class Acess control specifier fields methods classes COUSE CONTENT Inheritance Abstract classes Interfaces instanceof
More informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationCS 251 Intermediate Programming More on classes
CS 251 Intermediate Programming More on classes Brooke Chenoweth University of New Mexico Spring 2018 Empty Class public class EmptyClass { Has inherited methods and fields from parent (in this case, Object)
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationJava: introduction to object-oriented features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More informationOVERRIDING. 7/11/2015 Budditha Hettige 82
OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of
More informationInstance Members and Static Members
Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these
More informationObject Orientation Fourth Story. Bok, Jong Soon
Object Orientation Fourth Story Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr abstract Methods Java allows you to specify that a superclass declares a method that does not supply an implementation.
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(b): Abstract classes & Polymorphism Lecture Contents 2 Abstract base classes Concrete classes Polymorphic processing Dr. Amal Khalifa,
More informationProgramming overview
Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationPackages Inner Classes
Packages Inner Classes Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning - Topics
More informationInheritance and Interfaces
Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical
More informationCompaq Interview Questions And Answers
Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not
More informationJava 8 Programming for OO Experienced Developers
www.peaklearningllc.com Java 8 Programming for OO Experienced Developers (5 Days) This course is geared for developers who have prior working knowledge of object-oriented programming languages such as
More informationJava Primer. CITS2200 Data Structures and Algorithms. Topic 2
CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationSubclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented
Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and
More informationAgenda. Objects and classes Encapsulation and information hiding Documentation Packages
Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationObjectives. Describe ways to create constants const readonly enum
Constants Objectives Describe ways to create constants const readonly enum 2 Motivation Idea of constant is useful makes programs more readable allows more compile time error checking 3 Const Keyword const
More informationEnumerated Types. CSE 114, Computer Science 1 Stony Brook University
Enumerated Types CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Enumerated Types An enumerated type defines a list of enumerated values Each value is an identifier
More informationa guide to an object oriented programming language Niket Sheth JAVA
a guide to an object oriented programming language Niket Sheth JAVA Agenda History of Java OOP Using Java Features of Java 4Closing Remarks Outline of Java History of Java Brief History Of How Java Came
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationDay 4. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information
More informationWhat is Inheritance?
Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting
More informationInheritance and Polymorphism
Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationIndex COPYRIGHTED MATERIAL
Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes
More informationJava How to Program, 8/e
Java How to Program, 8/e Polymorphism Enables you to program in the general rather than program in the specific. Polymorphism enables you to write programs that process objects that share the same superclass
More informationThe Essence of OOP using Java, Nested Top-Level Classes. Preface
The Essence of OOP using Java, Nested Top-Level Classes Baldwin explains nested top-level classes, and illustrates a very useful polymorphic structure where nested classes extend the enclosing class and
More informationFast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview
Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3 Course Code: GK1965 Overview Java 8 Essentials for OO Developers is a three-day, fast-paced, quick start to Java 8 training
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationAP Computer Science Chapter 10 Implementing and Using Classes Study Guide
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within
More informationObject-Oriented Programming
iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 40 Overview 1 2 3 4 5 2 / 40 Primary OOP features ion: separating an object s specification from its implementation. Encapsulation: grouping related
More informationOBJECT ORİENTATİON ENCAPSULATİON
OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual
More informationAbstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.
a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must
More informationCO Java SE 8: Fundamentals
CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator
More informationAtelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.
marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationComputer Science II (20073) Week 1: Review and Inheritance
Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system
More informationInheritance (Outsource: )
(Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,
More informationRelationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor
CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog
More informationSoftware Paradigms (Lesson 3) Object-Oriented Paradigm (2)
Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3
More informationCOMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016
COMP-202: Foundations of Programming Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 Review What is the difference between a while loop and an if statement? What is an off-by-one
More informationIndex. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107
A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105
More informationInheritance (continued) Inheritance
Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses
More informationWA1278 Introduction to Java Using Eclipse
Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java
More informationCISC370: Inheritance
CISC370: Inheritance Sara Sprenkle 1 Questions? Review Assignment 0 due Submissions CPM Accounts Sara Sprenkle - CISC370 2 1 Quiz! Sara Sprenkle - CISC370 3 Inheritance Build new classes based on existing
More informationChapter 5 Object-Oriented Programming
Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares
More informationReviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand
More informationChapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,
Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design
More informationCS-202 Introduction to Object Oriented Programming
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction
More informationRelationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor
CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog
More informationCloning Enums. Cloning and Enums BIU OOP
Table of contents 1 Cloning 2 Integer representation Object representation Java Enum Cloning Objective We have an object and we need to make a copy of it. We need to choose if we want a shallow copy or
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationOOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.
OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.
More informationThe Sun s Java Certification and its Possible Role in the Joint Teaching Material
The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified
More informationInheritance and Polymorphism
Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html
More informationObject Oriented Programming
Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented
More informationAgenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda
More informationCore Java - SCJP. Q2Technologies, Rajajinagar. Course content
Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code
More informationJavaScript: Sort of a Big Deal,
: Sort of a Big Deal, But Sort of Quirky... March 20, 2017 Lisp in C s Clothing (Crockford, 2001) Dynamically Typed: no static type annotations or type checks. C-Like Syntax: curly-braces, for, semicolons,
More informationLTBP INDUSTRIAL TRAINING INSTITUTE
Java SE Introduction to Java JDK JRE Discussion of Java features and OOPS Concepts Installation of Netbeans IDE Datatypes primitive data types non-primitive data types Variable declaration Operators Control
More informationThe Java Programming Language
The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation
More informationInheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes
Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationPractice for Chapter 11
Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing
More informationChapter 4 Java Language Fundamentals
Chapter 4 Java Language Fundamentals Develop code that declares classes, interfaces, and enums, and includes the appropriate use of package and import statements Explain the effect of modifiers Given an
More informationCH. 2 OBJECT-ORIENTED PROGRAMMING
CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED
More informationRelationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.
CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches
More information9 Working with the Java Class Library
9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and
More information