关于upcasting,高手高手高高手进,谢谢!

ddxxtt 2007-03-17 02:08:13
class SuperClass{
int a;
public SuperClass(){a=12;System.out.println("1"+a);}
void test(){System.out.println("this is the super!");}
}

class SubClass extends SuperClass{
int a;
public SubClass(){a=13;System.out.println("2"+a);}
void test(){System.out.println("This is the subclass");}
}

public class Test{
public static void main(String args[]){
SuperClass temp = new SubClass();
temp.test();
System.out.println(temp.a);}
}

这段代码有两个问题想请教一下:
一、为什么System.out.println(temp.a);这句输出的是12?temp不是一个指向SubClass的SuperClass类型的句柄马?如果这么理解不是应该输出的是13马?temp.test();输出的不就是SubClass里的方法吗?

二、如果SuperClass中test,改写成private void test() eclispe会抱错,又没有调用SuperClass中的test方法,为什么会抱错呢?谢谢大家拉!
...全文
261 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
kaiser288977 2007-10-19
  • 打赏
  • 举报
回复
SuperClass temp = new SubClass();这样定义后,在内存中是有几个对象呢?是一个还是二个?还请大手们指教。
创建两个对象,从JAVA虚拟机的角度讲,temp是一个类引用变量,new SubClass()是一个类引用。
对于用父类指向子类对象,主要的一点就是父引用变量只能访问到它本身定义的所有对象,而它不知道其子类又重新定
义了哪些属性和方法,所以才会得到这样的结果。
yeah920 2007-03-19
  • 打赏
  • 举报
回复
up
interpb 2007-03-19
  • 打赏
  • 举报
回复
只有一个对象

但是子类的对象包含相应的父类对象
liuguangyi12 2007-03-19
  • 打赏
  • 举报
回复
SuperClass temp = new SubClass();这样定义后,在内存中是有几个对象呢?是一个还是二个?还请大手们指教。
cll0320 2007-03-17
  • 打赏
  • 举报
回复
同意楼上的
面向对象语言的多态性只是针对函数而言
对于属性来说,基类与派生类没有重载的可能性。并且是用SuperClass还是SubClass中的属性,在编译期间就已经确定下来了。
也就是说如果你写System.out.println(((SubClass)temp).a);
做个类型转化,那么输出的就是13了
interpb 2007-03-17
  • 打赏
  • 举报
回复
一、为什么System.out.println(temp.a);这句输出的是12?temp不是一个指向SubClass的SuperClass类型的句柄马?如果这么理解不是应该输出的是13马?temp.test();输出的不就是SubClass里的方法吗?



属性是不具有多态性的 你是声明的什么类型 调用属性调用相应类的属性
temp被声明为SuperClass 调用它的a就是SuperClass的a

调用test的时候 因为方法的多态性 这时候时SubClass的



二、如果SuperClass中test,改写成private void test() eclispe会抱错,又没有调用SuperClass中的test方法,为什么会抱错呢?谢谢大家拉!

你通过tmp调用test方法 首先起码要SuperClass的这个方法 你可以访问,然后才涉及到多态
你既然设为private 肯定就不能调用了

虽然你是调用Sub的方法但是你是通过Super调用的 起码这个入口你要有权限
What’s Inside Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4th edition........................ 2 Changes .......................................... 3 Note on the cover design ....... 4 Acknowledgements ................ 4 Introduction 9 Prerequisites .......................... 9 Learning Java ....................... 10 Goals ..................................... 10 Teaching from this book ....... 11 JDK HTML documentation ...................... 11 Exercises ............................... 12 Foundations for Java ............ 12 Source code ........................... 12 Coding standards ......................... 14 Errors .................................... 14 Introduction to Objects 15 The progress of abstraction ........................ 15 An object has an interface ........................... 17 An object provides services ................... 18 The hidden implementation .................... 19 Reusing the implementation ................... 20 Inheritance............................ 21 Is-a vs. is-like-a relationships ......24 Interchangeable objects with polymorphism ............. 25 The singly rooted hierarchy .............................. 28 Containers ............................ 28 Parameterized types (Generics) ..29 Object creation & lifetime ... 30 Exception handling: dealing with errors ............... 31 Concurrent programming ... 32 Java and the Internet .......... 33 What is the Web? ......................... 33 Client-side programming ............ 34 Server-side programming ............ 38 Summary .............................. 38 Everything Is an Object 41 You manipulate objects with references ..................... 41 You must create all the objects ....................... 42 Where storage lives ...................... 42 Special case: primitive types ....... 43 Arrays in Java .............................. 44 You never need to destroy an object .................. 45 Scoping ........................................ 45 Scope of objects ........................... 46 Creating new data types: class ..................................... 46 Fields and methods ..................... 47 Methods, arguments, and return values ................. 48 The argument list ......................... 49 Building a Java program ...... 50 Name visibility ............................. 50 Using other components ............. 50 The static keyword ..................... 51 Your first Java program ....... 52 Compiling and running ............... 54 Comments and embedded documentation ..................... 55 Comment documentation ............ 55 Syntax .......................................... 56 Embedded HTML ........................ 56 Some example tags ...................... 57 Documentation example ............. 59 Coding style .......................... 60 Summary .............................. 60 Exercises .............................. 60 Operators 63 Simpler print statements ..... 63 Using Java operators ........... 64 Precedence ........................... 64 Assignment .......................... 65 Aliasing during method calls ....... 66 Mathematical operators....... 67 Unary minus and plus operators ....................... 68 Auto increment and decrement ............................ 69 Relational operators ............ 70 Testing object equivalence ........... 70 Logical operators .................. 71 Short-circuiting ............................ 72 Literals .................................. 73 Exponential notation ................... 74 Bitwise operators .................. 75 Shift operators ......................76 Ternary if-else operator ......79 String operator + and += .............................. 80 Common pitfalls when using operators ........... 81 Casting operators .................. 81 Truncation and rounding ........... 82 Promotion ................................... 83 Java has no “sizeof” ............. 83 A compendium of operators .......................... 84 Summary ............................... 91 Controlling Execution 93 true and false..................... 93 if-else .................................. 93 Iteration ............................... 94 do-while ..................................... 95 for ................................................ 95 The comma operator................... 96 Foreach syntax ......................97 return ................................. 99 break and continue .......... 99 The infamous “goto” ........... 101 switch ................................104 Summary ............................ 106 Initialization & Cleanup 107 Guaranteed initialization with the constructor ........... 107 Method overloading .......... 109 Distinguishing overloaded methods .................. 110 Overloading with primitives ....... 111 Overloading on return values .... 114 Default constructors ........... 114 The this keyword ............... 116 Calling constructors from constructors ...................... 118 The meaning of static ............... 119 Cleanup: finalization and garbage collection ........ 119 What is finalize() for? ............. 120 You must perform cleanup ......... 121 The termination condition ......... 121 How a garbage collector works .. 122 Member initialization ......... 125 Specifying initialization ............. 126 Constructor initialization ... 127 Order of initialization ................ 127 static data initialization ........... 128 Explicit static initialization ...... 130 Non-static instance initialization ................ 132 Array initialization ............. 133 Variable argument lists ............. 137 Enumerated types ............... 141 Summary ............................ 143 Access Control 145 package: the library unit ................... 146 Code organization ...................... 147 Creating unique package names ........................... 148 A custom tool library .................. 151 Using imports to change behavior ..................... 152 Package caveat ........................... 153 Java access specifiers .......... 153 Package access ........................... 153 public: interface access ............ 154 private: you can’t touch that! .. 155 protected: inheritance access . 156 Interface and implementation .......... 158 Class access ........................ 159 Summary ............................ 162 Reusing Classes 165 Composition syntax ........... 165 Inheritance syntax ............. 168 Initializing the base class ........... 169 Delegation ........................... 171 Combining composition and inheritance ................... 173 Guaranteeing proper cleanup .... 174 Name hiding ............................... 177 Choosing composition vs. inheritance .................... 178 protected ......................... 180 Upcasting ............................ 181 Why “upcasting”? ...................... 181 Composition vs. inheritance revisited ..................................... 182 The final keyword ............. 182 final data ................................... 183 final methods ............................ 186 final classes ............................... 187 final caution .............................. 188 Initialization and class loading ................ 189 Initialization with inheritance ... 189 Summary ............................. 191 Polymorphism 193 Upcasting revisited ............. 193 Forgetting the object type .......... 194 The twist ............................. 196 Method-call binding .................. 196 Producing the right behavior ..... 196 Extensibility ............................... 199 Pitfall: “overriding” private methods ...................... 202 Pitfall: fields and static methods .................. 203 Constructors and polymorphism ................... 204 Order of constructor calls ......... 204 Inheritance and cleanup ........... 206 Behavior of polymorphic methods inside constructors .... 210 Covariant return types ........ 211 Designing with inheritance .................. 212 Substitution vs. extension ......... 213 Downcasting and runtime type information ......... 215 Summary ............................. 217 Interfaces 219 Abstract classes and methods ....................... 219 Interfaces ........................... 222 Complete decoupling ......... 225 “Multiple inheritance” in Java ................................ 230 Extending an interface with inheritance .......................... 231 Name collisions when combining Interfaces ................233 Adapting to an interface .... 234 Fields in interfaces ............ 235 Initializing fields in interfaces .. 236 Nesting interfaces .............. 237 Interfaces and factories ..... 239 Summary ............................. 241 Inner Classes 243 Creating inner classes ........ 243 The link to the outer class .................... 244 Using .this and .new ........ 246 Inner classes and upcasting ..................... 247 Inner classes in methods and scopes ........... 249 Anonymous inner classes ........................ 251 Factory Method revisited .......... 254 Nested classes .................... 256 Classes inside interfaces ............ 257 Reaching outward from a multiplynested class ............... 259 Why inner classes? ............. 259 Closures & callbacks .................. 261 Inner classes & control frameworks ................... 263 Inheriting from inner classes ....................... 269 Can inner classes be overridden? ................... 269 Local inner classes .............. 271 Inner-class identifiers ........ 272 Summary ............................ 273 Holding Your Objects 275 Generics and type-safe containers ........... 276 Basic concepts .................... 278 Adding groups of elements ......................... 279 Printing containers ............ 281 List ..................................... 283 Iterator ............................. 286 ListIterator ............................ 288 LinkedList ....................... 289 Stack ................................. 291 Set ...................................... 292 Map ................................... 295 Queue ................................ 298 PriorityQueue ........................ 299 Collection vs. Iterator ... 301 Foreach and iterators ......... 304 The Adapter Method idiom ...... 306 Summary ............................ 308 Error Handling with Exceptions 313 Concepts ............................. 313 Basic exceptions.................. 314 Exception arguments ................. 315 Catching an exception ........ 315 The try block ............................. 316 Exception handlers .................... 316 Creating your own exceptions ................... 317 Exceptions and logging .............. 319 The exception specification ....................... 322 Catching any exception ..... 323 The stack trace .......................... 324 Rethrowing an exception ........... 325 Exception chaining .................... 327 Standard Java exceptions .......................... 330 Special case: RuntimeException ............... 330 Performing cleanup with finally ....................... 332 What’s finally for? .................... 333 Using finally during return .... 335 Pitfall: the lost exception .......... 336 Exception restrictions ....... 338 Constructors ...................... 340 Exception matching ........... 344 Alternative approaches ...... 345 History ...................................... 346 Perspectives ............................... 347 Passing exceptions to the console ............................ 349 Converting checked to unchecked exceptions ........... 350 Exception guidelines ......... 352 Summary ............................ 352 Strings 355 Immutable Strings ............355 Overloading ‘+’ vs. StringBuilder ................. 356 Unintended recursion ....... 359 Operations on Strings ....... 361 Formatting output ............. 362 printf() .................................... 363 System.out.format() ............ 363 The Formatter class ............... 363 Format specifiers ...................... 364 Formatter conversions ........... 366 String.format() ..................... 368 Regular expressions ........... 370 Basics .........................................370 Creating regular expressions ..... 372 Quantifiers ................................. 374 Pattern and Matcher ............. 375 split() ........................................382 Replace operations .................... 383 reset() .......................................384 Regular expressions and Java I/O .............................. 385 Scanning input ................... 386 Scanner delimiters ................. 388 Scanning with regular expressions ................... 389 StringTokenizer ............. 389 Summary ............................ 391 Type Information 393 The need for RTTI .............. 393 The Class object ................ 395 Class literals ............................... 399 Generic class references ............ 401 New cast syntax ........................ 403 Checking before a cast ....... 404 Using class literals .................... 409 A dynamic instanceof .............. 411 Counting recursively .................. 412 Registered factories ........... 413 instanceof vs. Class equivalence......................... 416 Reflection: runtime class information ................ 417 A class method extractor ........... 418 Dynamic proxies ................ 420 Null Objects ........................ 424 Mock Objects & Stubs ................ 429 Interfaces and type information ................ 430 Summary ............................ 436 Generics 439 Comparison with C++ ........ 440 Simple generics .................. 440 A tuple library ............................ 442 A stack class ............................... 444 RandomList ............................ 445 Generic interfaces .............. 446 Generic methods ................ 449 Leveraging type argument inference ...................450 Varargs and generic methods .... 452 A generic method to use with Generators............ 453 A general-purpose Generator . 453 Simplifying tuple use ................. 455 A Set utility................................ 456 Anonymous inner classes ....................... 459 Building complex models ................. 460 The mystery of erasure ...... 462 The C++ approach .................... 464 Migration compatibility ............ 466 The problem with erasure ......... 467 The action at the boundaries .... 468 Compensating for erasure ........................... 471 Creating instances of types ........ 472 Arrays of generics ...................... 475 Bounds ............................... 479 Wildcards ........................... 482 How smart is the compiler? ...... 484 Contravariance .......................... 485 Unbounded wildcards ............... 488 Capture conversion ................... 492 Issues ................................. 493 No primitives as type parameters .................... 493 Implementing parameterized interfaces ........... 495 Casting and warnings ............... 496 Overloading ............................... 498 Base class hijacks an interface .. 498 Self-bounded types ............ 500 Curiously recurring generics .... 500 Self-bounding ............................ 501 Argument covariance ................ 503 Dynamic type safety .......... 506 Exceptions ......................... 507 Mixins ................................ 509 Mixins in C++ ........................... 509 Mixing with interfaces ............... 510 Using the Decorator pattern ....... 511 Mixins with dynamic proxies .... 512 Latent typing ....................... 514 Compensating for the lack of latent typing ...... 518 Reflection ................................... 518 Applying a method to a sequence .............................. 519 When you don’t happen to have the right interface .......... 521 Simulating latent typing with adapters ............................. 523 Using function objects as strategies ....................... 526 Summary: Is casting really so bad? ...................... 531 Further reading .......................... 533 Arrays 535 Why arrays are special ........535 Arrays are first-class objects ............... 536 Returning an array ............. 539 Multidimensional arrays .................................. 540 Arrays and generics ........... 543 Creating test data ............... 546 Arrays.fill() ............................. 546 Data Generators ...................... 547 Creating arrays from Generators ..................... 551 Arrays utilities .................. 555 Copying an array ........................ 555 Comparing arrays ...................... 556 Array element comparisons ...... 557 Sorting an array .........................560 Searching a sorted array ............ 561 Summary ............................ 564 Containers in Depth 567 Full container taxonomy .... 567 Filling containers ............... 568 A Generator solution .............. 569 Map generators ......................... 570 Using Abstract classes ............. 573 Collection functionality ....................... 580 Optional operations ........... 582 Unsupported operations............ 583 List functionality ............... 586 Sets and storage order ...... 589 SortedSet ................................. 591 Queues ................................ 594 Priority queues ........................... 594 Deques ....................................... 595 Understanding Maps ........ 598 Performance .............................. 599 SortedMap ............................. 602 LinkedHashMap ................... 603 Hashing and hash codes .... 605 Understanding hashCodeQ .... 607 Hashing for speed ...................... 610 Overriding hashCode() ........... 613 Choosing an implementation .............. 617 A performance test framework ........................... 618 Choosing between Lists ............ 621 Microbenchmarking dangers .... 626 Choosing between Sets ............. 627 Choosing between Maps ........... 629 Utilities ............................... 632 Sorting and searching Lists ...... 635 Making a Collection or Map unmodifiable ............... 636 Synchronizing a Collection or Map ................... 637 Holding references ............ 639 The WeakHashMap .............. 640 Java 1.0/1.1 containers ...... 642 Vector & Enumeration ........ 642 Hashtable ............................... 643 Stack ........................................ 643 BitSet ....................................... 644 Summary ............................ 646 I/O 647 The File class .................... 647 A directory lister ........................ 647 Directory utilities ...................... 650 Checking for and creating directories ............. 654 Input and output ............... 656 Types of InputStream ............. 657 Types of OutputStream ......... 658 Adding attributes and useful interfaces .......... 659 Reading from an InputStream with FilterlnputStream ........ 660 Writing to an OutputStream with FilterOutputStream ...... 661 Readers & Writers ......... 662 Sources and sinks of data ......... 662 Modifying stream behavior ...... 663 Unchanged classes .................... 664 Off by itself: RandomAccessFile ....... 665 Typical uses of I/O streams .................... 665 Buffered input file ...................... 665 Input from memory .................. 666 Formatted memory input .......... 667 Basic file output ........................ 668 Storing and recovering data ..... 669 Reading and writing random-access files .................. 670 Piped streams ............................ 672 File reading & writing utilities ............... 672 Reading binary files ................... 674 Standard I/O ....................... 675 Reading from standard input .... 675 Changing System.out to a PrintWriter ...................... 676 Redirecting standard I/O .......... 676 Process control ................... 677 New I/O ............................. 679 Converting data.......................... 681 Fetching primitives ................... 684 View buffers ............................... 685 Data manipulation with buffers ............................... 688 Buffer details ............................. 689 Memory-mapped files ............... 692 File locking ................................. 695 Compression ...................... 698 Simple compression with GZIP .................................. 698 Multifile storage with Zip .......... 699 Java ARchives (JARs) ................ 701 Object serialization ............ 703 Finding the class ........................ 706 Controlling serialization ............ 707 Using persistence ....................... 713 XML .................................... 718 Preferences .......................... 721 Summary ............................ 722 Enumerated Types 725 Basic enum features ......... 725 Using static imports with enums ............................... 726 Adding methods to an enum ........................ 727 Overriding enum methods ....... 728 enums in switch statements ............. 728 The mystery of values() ........................ 729 Implements, not inherits ......................... 732 Random selection .............. 732 Using interfaces for organization .................. 734 Using EnumSet instead of flags ................... 737 Using EnumMap ............. 739 Constant-specific methods .............................. 740 Chain of Responsibility with enums ............................... 743 State machines with enums ..... 746 Multiple dispatching ........... 751 Dispatching with enums .......... 753 Using constant-specific methods ......... 755 Dispatching with EnumMaps ...................... 756 Using a 2-D array ....................... 757 Summary ............................ 759 Annotations 761 Basic syntax ....................... 762 Defining annotations ................. 762 Meta-annotations ...................... 763 Writing annotation processors ........ 765 Annotation elements ................. 765 Default value constraints ........... 766 Generating external files............ 766 Annotations don’t support inheritance ................... 769 Implementing the processor...... 769 Using apt to process annotations ............ 772 Using the Visitor pattern with apt .............................. 775 Annotation-based unit testing .......................... 778 Using @Unit with generics ....... 785 No “suites” necessary .................786 Implementing @Unit ............... 787 Removing test code .................... 792 Summary ............................. 795 Concurrency 797 The many faces of concurrency ....................... 798 Faster execution .........................798 Improving code design ............. 800 Basic threading .................. 801 Defining tasks ............................ 801 The Thread class ..................... 802 Using Executors ..................... 804 Producing return values from tasks ................................. 806 Sleeping ..................................... 808 Priority ...................................... 809 Yielding ...................................... 810 Daemon threads ......................... 810 Coding variations ....................... 814 Terminology ............................... 819 Joining a thread ......................... 819 Creating responsive user interfaces ............................ 821 Thread groups ........................... 822 Catching exceptions .................. 822 Sharing resources .............. 824 Improperly accessing resources ................... 825 Resolving shared resource contention ................... 827 Atomicity and volatility ............. 831 Atomic classes ........................... 836 Critical sections .......................... 837 Synchronizing on other objects .............................. 841 Thread local storage ..................843 Terminating tasks .............. 844 The ornamental garden ............ 844 Terminating when blocked ........ 847 Interruption .............................. 848 Checking for an interrupt .......... 854 Cooperation between tasks ..................... 856 wait() and notifyAll() ............ 857 notify() vs. notifyAll() ........... 861 Producers and consumers ........ 863 Producer-consumers and queues ................................ 868 Using pipes for I/O between tasks ............................. 872 Deadlock ............................. 874 New library components ........................ 879 CountDownLatch .................. 879 CyclicBarrier .......................... 881 DelayQueue ........................... 883 PriorityBlockingQueue....... 885 The greenhouse controller with ScheduledExecutor ...... 887 Semaphore ............................. 890 Exchanger .............................. 893 Simulation .......................... 896 Bank teller simulation .............. 896 The restaurant simulation ........ 900 Distributing work ..................... 904 Performance tuning ........... 909 Comparing mutex technologies ................... 909 Lock-free containers .................. 916 Optimistic locking...................... 922 ReadWriteLocks .................... 923 Active objects ..................... 925 Summary ............................ 929 Further reading .......................... 931 Graphical User Interfaces 933 Applets ............................... 935 Swing basics ....................... 935 A display framework .................. 937 Making a button ................. 938 Capturing an event ............. 939 Text areas ........................... 941 Controlling layout .............. 942 BorderLayout ......................... 942 FlowLayout ............................. 943 GridLayout .............................. 944 GridBagLayout....................... 944 Absolute positioning .................. 945 BoxLayout ............................... 945 The best approach? .................... 945 The Swing event model ..... 945 Event and listener types ........... 946 Tracking multiple events ........... 951 A selection of Swing components ............ 953 Buttons ....................................... 953 Icons .......................................... 955 Tool tips ..................................... 957 Text fields ................................... 957 Borders ....................................... 959 A mini-editor.............................. 959 Check boxes .............................. 960 Radio buttons ............................. 961 Combo boxes (drop-down lists) ...................... 962 List boxes .................................. 963 Tabbed panes ............................. 965 Message boxes ........................... 965 Menus ......................................... 967 Pop-up menus ............................ 972 Drawing ...................................... 973 Dialog boxes ............................... 975 File dialogs .................................978 HTML on Swing components .................... 980 Sliders and progress bars ......... 980 Selecting look & feel ................... 981 Trees, tables & clipboard .......... 983 JNLP and Java Web Start ................... 983 Concurrency & Swing ........ 988 Long-running tasks ................... 988 Visual threading ........................ 994 Visual programming and JavaBeans ................... 996 What is a JavaBean? ................. 996 Extracting Beanlnfo with the Introspector ............ 998 A more sophisticated Bean ..... 1002 JavaBeans and synchronization ....................... 1005 Packaging a Bean .................... 1008 More complex Bean support .. 1009 More to Beans .......................... 1010 Alternatives to Swing ........ 1010 Building Flash Web clients with Flex ................ 1011 Hello, Flex ................................. 1011 Compiling MXML .................... 1012 MXML and ActionScript.......... 1013 Containers and controls........... 1013 Effects and styles ..................... 1015 Events ....................................... 1016

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧