码迷,mamicode.com
首页 > 编程语言 > 详细

Java面向对象小记(2)

时间:2015-06-06 23:38:01      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:java

1. 继承


用一个例子说明继承

class Person{
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void tell(){
		System.out.println("name:"+ this.getName()+" "+"age:"+this.getAge());
	}
}

class Student extends Person{
	private int score;

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}
	public void tell(){
		super.tell();  //使用父类方法
		System.out.println("score:"+score);
	}
}
public class ExtendDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student std = new Student();
		std.setAge(20);
		std.setName("thystar");
		std.setScore(100);
		std.tell();
	}

}


2 抽象类和借口

final关键字 声明类,方法,和属性

  • 使用final声明的类不能被继承

  • 使用final声明的方法不能被重写

  • 使用final声明的变量变成常量,常量不能修改


抽象类 : 包含抽象方法的类

     abstract class className{

    }


    抽象方法:声明而未被实现的方法,用abstract关键字声明

    抽象类被子类继承,要重写抽象类中的所有方法

    抽象类不能直接实例化,要通过其子类实例化

abstract class Abs{
	private int age;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void tell(){}
	public abstract void say();
	public abstract void print();
}

class AbsClass extends Abs{
	public void say(){
		System.out.println(this.getAge());
	}
	public void print(){
		
	}
}

public class AbsDemo {
	public static void main(String[] args){
		AbsClass ab = new AbsClass();
		ab.setAge(20);
		ab.say();
	}
}


接口:

    interface interName{

}


interface Inter{
	public static final int AGE=10;//公共全局常量
	public abstract void tell();
}

interface Inter2{
	public abstract void say();
}

abstract class Abs1{
	public abstract void print();
}

class A extends Abs implements Inter, Inter2{
	public void tell(){
		
	}
	public void say(){
		System.out.println("say");
	}
	public void print(){
		System.out.println("Abs");
	}
}

public class InterDemo01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		A a = new A();
		a.tell();
		System.out.println(Inter.AGE);    //全局常量用类名调用
		a.say();
		a.print();
	}

}



极客学院课程:http://www.jikexueyuan.com/path/javaweb/











Java面向对象小记(2)

标签:java

原文地址:http://4440271.blog.51cto.com/4430271/1659292

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!