阅读书目:Java入门经典(第7版) 做者:罗格斯·卡登海德java
面向对象编程(OOP)将程序视为对象的集合,肯定程序要完成的任务,而后将这些任务指派给最适合完成它们的对象。换言之,计算机程序是一组对象,这些对象协同工做以完成某项任务,有些简单程序看似只有一个对象(类文件)组成,但实际上也使用了其余对象来完成工做。程序员
在面向对象编程中,对象包含两项内容:属性和行为,属性描述对象并使其不一样于其余对象,而行为指的是对象能作什么。编程
1 package com.java24hours; 2 3 public class Modem { 4 int speed; 5 6 public void displaySpeed() { 7 System.out.println("speed: "+speed); 8 } 9 }
经过继承,程序员只需定义新类与现有类的不一样之处,就可以建立一个新类。继承其余类可使用extends语句。spa
1 package com.java24hours; 2 3 public class ErrorCorrectModem extends Modem { 4 //继承Modem类 5 }
咱们称从其余类继承而来的类为子类,被继承的类为超类。Java中存在大量的继承,进而造成继承层次。code
简单变量类型转换示例:对象
int destination = (int)source;
对象间的类型转换:能够在任何须要超类的地方使用类对象。也能够将对象用于须要其子类的地方,但因为子类含有更多信息,若是程序使用对象没有包含的子类方法,将致使错误。将类型用于须要子类的地方,须要进行显式地类型转换。blog
1 public void paintComponent(Graphics comp){ 2 Graphics2D comp2D = (Graphics2D) comp; 3 }
简单变量和对象之间的类型转换,例如:继承
Integer suffix = new Integer(5396); int newSuffix = suffix.intValue();
String count = "25"; int myCount = Integer.parseInt(count);
1 package com.java24hours; 2 3 public class NewRoot { 4 public static void main(String[] arguments) { 5 int number = 100; 6 if(arguments.length>0) { 7 number = Integer.parseInt(arguments[0]); 8 } 9 System.out.println("The square root of " 10 +number 11 +" is " 12 +Math.sqrt(number) 13 ); 14 } 15 }
Java的自动封装功能将简单变量值转换为相对应的类,封装功能将对象转换为相对应的简单变量值。io
在如今的Java版本中,以下的语句也是合法的语句:面向对象编程
Float total = new 1.3F; float sum = total/5; Integer suffix = 5309;
建立对象:
1 package com.java24hours; 2 3 public class Modem { 4 int speed; 5 6 public void displaySpeed() { 7 System.out.println("speed: "+speed); 8 } 9 }
1 package com.java24hours; 2 3 public class CableModem extends Modem{ 4 String method = "cable connection"; 5 6 public void connect() { 7 System.out.println("Connecting to the Internet..."); 8 System.out.println("Using a " 9 +method); 10 } 11 }
1 package com.java24hours; 2 3 public class DslModem extends Modem{ 4 String method = "DSL phone connection"; 5 6 public void connect() { 7 System.out.println("Connecting to the Internet..."); 8 System.out.println("Using a " 9 +method); 10 } 11 }
1 package com.java24hours; 2 3 public class ModemTester { 4 public static void main(String[] arguements) { 5 CableModem surfBoard = new CableModem(); 6 DslModem gateway = new DslModem(); 7 surfBoard.speed = 5_000_000; 8 gateway.speed = 4_000_000; 9 System.out.println("Trying the cable modem: "); 10 surfBoard.displaySpeed(); 11 surfBoard.connect(); 12 System.out.println("Trying the DSL modem "); 13 gateway.displaySpeed(); 14 gateway.connect(); 15 } 16 }
Java不像C++中一个类能够继承多个类,任何一个类只有一个超类。