Java程序设计 # 2

  • 文章如有错误或疏漏之处还请不吝赐教
  • 本文假定读者已经掌握一门编程语言的基础,不适宜从未接触编程的同学
  • 欢迎母校同学前来打卡~

  • 面向对象三大特性:继承、封装、多态
  • 在构造方法中用this()调用另一构造方法,这句话必须写在最前面,这是一种特殊的调用,super()调用父类构造方法时也要写在第一句。
  • 父类对象与子类对象的转换

example:

class Person {
	String name;
	int age;

	Person( String n, int a ){
		name = n;
		age = a;
	}

	Person( String n ){
		name = n;
		age = 0;
	}

	Person( int age, String name )
	{
		this.age = age;
		this.name = name;
	}

	Person(  ){
		this( 0, "" );
	}

	boolean isOlderThan( int anAge ){
		return this.age > anAge;
	}

	void sayHello(){
		System.out.println("Hello! My name is " + name );
	}

	void sayHello( Person another ){
		System.out.println("Hello," + another.name 
			+ "! My name is " + name );
	}

	public static void main(String[] args) 
	{
		Person p = new Person("Li Min", 18);
		Person p2 = new Person("Wang Qiang", 20 );
		p.sayHello();
		p.sayHello(p2);
	}
}

class  Student extends Person
{
	String school;
	int score;

	void sayHello( Student another ){
		System.out.println("Hi!");
		if( school == another.school ) 
			System.out.println(" Shoolmates ");
	}

	boolean isGoodStudent(){
		return score>=90;
	}

	void sayHello(){
		super.sayHello();
		System.out.println( "My school is " + school );
	}

	Student(String name, int age, String school ){
		super( name, age );
		this.school = school;
	}

	Student(){}

	void testThisAndSuper(){
		int a;
		a = age;
		a = this.age;
		a = super.age;
	}

	public static void main( String [] arggs )
	{
		Person p = new Person( "Liming", 50 );
		Student s = new Student( "Wangqiang", 20, "PKU" );
		Person p2 = new Student( "Zhangyi", 18, "THU" );
		Student s2 = (Student) p2;

		//Student s3 = (Student) p;  //runtime exception  编译不报错

		p.sayHello( s );

		Person [] manypeople = new Person[ 100 ];
		manypeople[0] = new Person("Li", 18 );
		manypeople[1] = new Student("Wang", 18, "PKU");
	}
}
  • 成员访问控制符(权限修饰符)
  • setter/getter示例
class  Person2{
	private int age;
	public void setAge( int age ) throws Exception {
		if (age>=0 && age<200) this.age = age;
		else throw new Exception("invalid age");
	}
	public  int getAge(){
		return age;
	}
}
  • 非访问控制符
  • static方法中不能使用this或者super,调用static方法可以用类名也可也用具体的对象调用
  • import static比import更强的写法,如import static java.lang.System.*;这样使用后可以直接写out.println();(>JDK1.5)
  • 关于final:
  • 接口里面的方法省略的话默认是public,接口里定义的常量定义即具有public、static、final的属性
  • Java中源文件的名字必须与属性为public的类的类名完全相同(也就是说在一个java文件中public类只能由1个)
  • 字段变量与局部变量

    *局部变量不能被访问控制符修饰以及static修饰,但可以被final修饰。

*参考PKU-Java程序设计课程资料以及NCEPU-Java程序设计课程资料
*未经授权请勿转载

发布了634 篇原创文章 · 获赞 579 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/qq_33583069/article/details/103185588